package o2o.web.actions.wallet;

import com.jinyou.utils.common.*;
import com.jinyou.utils.security.EncrypMD5;
import jPush.dao.JPushMessage;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import notice.dao.NoticeType;
import o2o.cache.company.postman.PostCompanyMemory;
import o2o.cache.company.postman.PostmanSignCompanyMemory;
import o2o.cache.order.OrderInfoMemory;
import o2o.cache.order.OrderStatusMemory;
import o2o.cache.postman.CityPostmanMemory;
import o2o.cache.shop.ShopMemory;
import o2o.cache.sys.SysConfigDepositMemory;
import o2o.cache.tip.TipInfoMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.cache.user.UserPwdMemory;
import o2o.cache.wallet.UserWalletMemory;
import o2o.config.dao.UserDaoSql;
import o2o.config.dao.utils.DaoUtils;
import o2o.config.dao.utils.Expression;
import o2o.config.dao.utils.QueryCondition;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.common.ResultInfo;
import o2o.dao.PO.common.UserType;
import o2o.dao.PO.company.postman.PostCompanyInfo;
import o2o.dao.PO.company.postman.PostmanSignCompanyInfo;
import o2o.dao.PO.order.*;
import o2o.postman.model.CityPostman;
import o2o.company.model.ShopInfo;
import o2o.dao.PO.tip.TipInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.PO.wallet.*;
import o2o.dao.VO.common.FileUploadInfo;
import o2o.dao.VO.order.REFUND_APPLY_STATUS;
import o2o.dao.VO.postman.CityPostmanVO;
import o2o.dao.VO.shop.ShopInfoVO;
import o2o.dao.VO.user.UserInfoVO;
import o2o.dao.VO.wallet.UserWalletPopVO;
import o2o.dao.VO.wallet.UserWalletVO;
import o2o.service.company.postman.PostManSalaryService;
import o2o.system.data.SYS_CONFIG_PATH;
import o2o.system.data.SYS_SETTINGS;
import o2o.task.image.ImageService;
import o2o.utils.OrderUtils;
import o2o.utils.bankCardCheck.BACK_CARD_CHECK_RESULT_TYPE;
import o2o.utils.bankCardCheck.BackCardCheckResult;
import o2o.utils.bankCardCheck.BackCardCheckUtil;
import o2o.web.actions.company.SysCityCompanyMan;
import o2o.web.actions.notice.Notice;
import o2o.web.actions.order.thread.OrderThread;
import o2o.web.actions.shop.ShopWalletMan;
import o2o.web.actions.user.User;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

//钱包
@Controller
public class WalletAction {

    private static HashMap<String, Long> popDataMap = new HashMap<>();

    //------------------------用户
    //获取钱包余额
    @RequestMapping(method = RequestMethod.POST, value = "/user/wallet")
    @ResponseBody
    public String user_wallet(String token) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        UserWallet userWallet = getWallet(user.getUsername());

        return AjaxResult.successResult(userWallet);
    }


    // 管理端获取用户的余额信息
    @RequestMapping(method = RequestMethod.POST, value = "/admin/user/wallet/get/by/username")
    @ResponseBody
    public String user_wallet_info(String token, String username) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        UserInfo info = UserInfoMemory.getInstance().getUserInfo(username);
        if (info == null) {
            return AjaxResult.errorResult("未获到用户信息");
        }
        UserWallet userWallet = getWallet(info.getUsername());
        return AjaxResult.successResult(userWallet);
    }

    //绑定支付渠道
    @RequestMapping(method = RequestMethod.POST, value = "/admin/user/wallet/bind/by/username")
    @ResponseBody
    public String admin_user_wallet_pop(String token,
                                        String username,
                                        String alipay, String alipayRealName,
                                        String tenpay, String tenpayopenId, String tenpayRealName,
                                        String bankUserName, String bankName, String bankCard, String bankPhone) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (userInfo == null) {
            return AjaxResult.errorResult("未获取到用户信息");
        }

        ResultInfo resultInfo = bindWallet(userInfo,//用户绑定支付渠道
                alipay, alipayRealName,
                tenpay, tenpayopenId, tenpayRealName,
                bankUserName, bankName, bankCard, bankPhone);
        if (null != resultInfo && !resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }
        return AjaxResult.successResult();
    }


    //绑定支付渠道
    @RequestMapping(method = RequestMethod.POST, value = "/user/wallet/bind")
    @ResponseBody
    public String user_wallet_pop(String token,
                                  String alipay, String alipayRealName,
                                  String tenpay, String tenpayopenId, String tenpayRealName,
                                  String bankUserName, String bankName, String bankCard, String bankPhone) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        ResultInfo resultInfo = bindWallet(user,//用户绑定支付渠道
                alipay, alipayRealName,
                tenpay, tenpayopenId, tenpayRealName,
                bankUserName, bankName, bankCard, bankPhone);
        if (null != resultInfo && !resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }

        return AjaxResult.successResult();
    }

    //提现申请
    @RequestMapping(method = RequestMethod.POST, value = "/user/wallet/pop")
    @ResponseBody
    public String user_wallet_pop(String token, Double money, String channel, String payPassword) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        // 提现申请
        if (SYS_SETTINGS.VERIFY_PAYMENT_PASSWORD != null && 0 == 1 - SYS_SETTINGS.VERIFY_PAYMENT_PASSWORD) {
            if (payPassword == null || "".equals(payPassword)) {
                return AjaxResult.errorResult("请输入支付密码");
            }
            String getPayPassword = UserPwdMemory.getInstance().getPayPassword(user.getUsername());
            if (payPassword == null || "".equals(payPassword)) {
                return AjaxResult.errorResult("请先设置独立的支付密码");
            }
            // check
            try {
                payPassword = EncrypMD5.eccrypt(payPassword);
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.errorResult("提现失败，请联系管理员");
            }
            if (!getPayPassword.equals(payPassword)) {
                return AjaxResult.errorResult("支付密码错误，请重新输入");
            }
            // 验证密码成功 ：提现
        }
        // end
        ResultInfo resultInfo = moneyPop(user, money, channel, null);
        if (null != resultInfo && !resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }
        return AjaxResult.successResult();
    }


    //查看自己的提现申请记录
    @RequestMapping(method = RequestMethod.POST, value = "/user/wallet/pop/history")
    @ResponseBody
    public String user_wallet_pop_history(String token, Long createTime, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        List<UserWalletPop> list = listOfPop(user.getUsername(), createTime, size);
        if (!ValidateUtil.isAbsList(list)) {
            return AjaxResult.successResult(0, null);
        }

        return AjaxResult.successResult(list.size(), list);
    }


    //充值下单
    @RequestMapping(method = RequestMethod.POST, value = "/user/wallet/in/submit")
    @ResponseBody
    public String user_wallet_submit_order(String token, Double money, Integer type, String gameInfoJson) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNotAbsDouble(money)) {
            return AjaxResult.errorResult("请确认充值金额");
        }

        if (null == type) {
            type = ORDER_TYPE.WALLET_IN;
        }

        String orderNo = OrderUtils.getOrderNo();
        Long time = DateUtils.getCurrTime();

        Double awardMoney = 0d;


        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUsername(user.getUsername());
        orderInfo.setOrderStatus(ORDER_STATUS.SUBMIT);
        if (ValidateUtil.isNull(user.getName())) {
            orderInfo.setBuyer(user.getUsername());
        } else {
            orderInfo.setBuyer(user.getName());
        }
        orderInfo.setOrderType(type);
        orderInfo.setOrderNo(orderNo);
        orderInfo.setTotalPrice(money);//待支付金额
        orderInfo.setTotalMoney(money);//订单总金额 商品金额+配送费+打包费+未减奖励金
        orderInfo.setTotalGoodsMoney(money);//商品总金额
        orderInfo.setPacketPrice(0d);//餐盒费
        orderInfo.setAwardMoney(awardMoney);//奖励总金额
        orderInfo.setPlatformAwardMoney(awardMoney);//平台奖励金额
        orderInfo.setShopAwardMoney(0d);//商家奖励金额
        orderInfo.setTotalCount(1);//商品总个数
        orderInfo.setIsZiQu(1);
        orderInfo.setIsPaid(0);//是否已支付
        orderInfo.setShopId(-5l);
        orderInfo.setDelFlag(0);
        orderInfo.setCreateTime(time);
        orderInfo.setCreateUser(user.getUsername());
        if (type == ORDER_TYPE.WALLET_DEPOSIT_IN) { // 骑手充值押金
            orderInfo.setExtra3("postman"); // 添加标记为骑手缴押金
        }
        //订单状态
        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setOrderNo(orderNo);
        orderStatus.setCreateUser(user.getUsername());
        orderStatus.setCreateTime(time);

        try {
            UserDaoSql.getInstance().insertObj(PojoTables.OrderInfo, orderInfo);
            UserDaoSql.getInstance().insertObj(PojoTables.OrderStatus, orderStatus);
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("保存订单信息失败，稍后再试");
        }

        //缓存中增加
        OrderInfoMemory.getInstance().addOrderInfo(orderNo);
        OrderStatusMemory.getInstance().addStatus(orderNo);

        //检测是否在规定时间内支付
        OrderInfo info = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        OrderThread.map.put(orderNo, info);

        OrderSubmitResult orderSubmitResult = new OrderSubmitResult();
        orderSubmitResult.setSuccess(true);
        orderSubmitResult.setOrderNo(orderNo);
        orderSubmitResult.setOrderTotalMoney(money);
        orderSubmitResult.setMustPayMoney(money);
        orderSubmitResult.setAwardMoney(awardMoney);
        return AjaxResult.successResult(orderSubmitResult);
    }

    // 管理后台为用户线下充值
    @RequestMapping(method = RequestMethod.POST, value = "/admin/user/wallet/recharge")
    @ResponseBody
    public String admin_user_wallet_recharge(String token, Double money, Double awardMoney, String username) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasSuperAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        if (StringUtils.isBlank(username)) {
            return AjaxResult.errorResult("用户账号不能为空");
        }
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (userInfo == null) {
            return AjaxResult.errorResult("用户信息不存在,请稍后重试");
        }
        if (ValidateUtil.isNotAbsDouble(money)) {
            return AjaxResult.errorResult("请确认充值金额");
        }
        String orderNo = OrderUtils.getOrderNo();
        Long time = DateUtils.getCurrTime();
        if (ValidateUtil.isNotAbsDouble(awardMoney)) {
            awardMoney = 0.0d;
        }
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUsername(userInfo.getUsername());
        orderInfo.setOrderStatus(ORDER_STATUS.OVER);
        if (ValidateUtil.isNull(userInfo.getName())) {
            orderInfo.setBuyer(userInfo.getUsername());
        } else {
            orderInfo.setBuyer(userInfo.getName());
        }
        orderInfo.setOrderType(ORDER_TYPE.WALLET_IN);
        orderInfo.setOrderNo(orderNo);
        orderInfo.setTotalPrice(money);//待支付金额
        orderInfo.setTotalMoney(money);//订单总金额 商品金额+配送费+打包费+未减奖励金
        orderInfo.setTotalGoodsMoney(money);//商品总金额
        orderInfo.setPacketPrice(0d);//餐盒费
        orderInfo.setAwardMoney(awardMoney);//奖励总金额
        orderInfo.setPlatformAwardMoney(awardMoney);//平台奖励金额
        orderInfo.setShopAwardMoney(0d);//商家奖励金额
        orderInfo.setTotalCount(1);//商品总个数
        orderInfo.setIsZiQu(1);
        orderInfo.setIsPaid(0);//是否已支付
        orderInfo.setShopId(-5l);
        orderInfo.setDelFlag(0);
        orderInfo.setCreateTime(time);
        orderInfo.setCreateUser(user.getUsername());
        orderInfo.setPayType(PAY_TYPE.UNDERLINE); // 线下支付的
        //订单状态
        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setOrderNo(orderNo);
        orderStatus.setCreateUser(user.getUsername());
        orderStatus.setCreateTime(time);
        orderStatus.setOrderStatus(ORDER_STATUS.OVER);
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.OrderInfo, orderInfo);
            UserDaoSql.getInstance().insertObj(PojoTables.OrderStatus, orderStatus);
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("保存订单信息失败，稍后再试");
        }
        //钱包充值 直接给用户账号增加
        //增加流水
        UserWalletFlow walletFlow = new UserWalletFlow(username, UserType.USER, orderNo, orderInfo.getOrderType(), orderInfo.getTotalPrice(),
                orderInfo.getTotalPrice(), 1d, UserWalletFlowType.FLOW_INCOME,
                user.getUsername(), DateUtils.getCurrTime());
        walletFlow.setAwardMoney(orderInfo.getAwardMoney());

        //汇率
        if (null != SYS_SETTINGS.USE_MAIN_CURRENCY_PAY && 0 == SYS_SETTINGS.USE_MAIN_CURRENCY_PAY && ValidateUtil.isAbsDouble(SYS_SETTINGS.EXCHANGE_RATE)) {//是否使用主币支付 1使用主币支付 0使用外币支付
            walletFlow.setExchangeRate(SYS_SETTINGS.EXCHANGE_RATE);
            walletFlow.setFcOrderTotalMoney(JYMathDoubleUtils.mul(orderInfo.getTotalPrice(), SYS_SETTINGS.EXCHANGE_RATE));
            walletFlow.setFcMoney(JYMathDoubleUtils.mul(orderInfo.getTotalPrice(), SYS_SETTINGS.EXCHANGE_RATE));
            walletFlow.setFcAwardMoney(JYMathDoubleUtils.mul(orderInfo.getAwardMoney(), SYS_SETTINGS.EXCHANGE_RATE));
        }

        try {
            UserDaoSql.getInstance().insertObj(PojoTables.USER_WALLET_FLOW, walletFlow);//分成  用户充值流水
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("添加充值记录失败");
        }

        //余额增加
        ResultInfo resultInfo = UserWalletMan.saveOrUpdateUserWallet(username, UserType.USER, null, UserWalletMan.ADD, orderInfo.getTotalPrice(), orderInfo.getAwardMoney(), user.getUsername());
        if (null != resultInfo && !resultInfo.isSuccess()) {
            System.out.println("用户充值，更新余额错误:" + resultInfo.getError());
            return AjaxResult.errorResult("用户充值失败,请核实账户余额是否到账");
        }
        //缓存中增加
        OrderInfoMemory.getInstance().addOrderInfo(orderNo);
        OrderStatusMemory.getInstance().addStatus(orderNo);
        return AjaxResult.successResult();
    }

    //工人押金提现
    @RequestMapping(method = RequestMethod.POST, value = "/admin/deposit/pop/history")
    @ResponseBody
    public String user_wallet_pop_history_deposit(String token,
                                                  String username, // 工人（申请人）
                                                  Integer isDone,
                                                  Long startTime, Long endTime,   // 申请提现时间
                                                  String city,      // 地区
                                                  Long remitStatTime, Long remitEndTime, // 打款时间
                                                  String remitType, // 打款渠道
                                                  Long userRole, // 用户角色 1工人 2骑手 3商家
                                                  String cityAdmin,// 代理
                                                  Integer isExcel,    // 是否导出Excel
                                                  Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //验证是否有登录权限
        if (!User.getInstance().hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        if (null == isExcel) {
            isExcel = 0;
        }
        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }
        Long totalCount = 0l;

        String userType = "";
        if (userRole == 1) {
            // 工人
            userType = "  AND cp.type = 2 ";
        } else if (userRole == 2) {
            // 骑手
            userType = "  AND cp.type = 1 ";
        } else if (userRole == 3) {
            // 商家
            userType = "  AND uwp.userType = " + UserType.SHOP_OWNER + "";
        }
        String timeStr = "";
        if (null != startTime && null != endTime) {
            timeStr = " AND uwp.createTime BETWEEN " + startTime + " AND " + endTime + " ";
        }
        String remitTimeStr = "";
        if (null != remitStatTime && null != remitEndTime) {
            remitTimeStr = " AND uwp.popTime BETWEEN " + remitStatTime + " AND " + remitEndTime + " ";
        }
        String doneStr = "";
        if (null != isDone) {
            if (isDone != 0) {
                isDone = isDone == 2 ? 0 : (isDone == 1 ? 1 : 0);
                doneStr = " AND uwp.isDone = " + isDone + " ";
            }
        }
        String usernameStr = "";
        if (ValidateUtil.isNotNull(username)) {
            usernameStr = " AND uwp.username = " + username + " ";
        }
        String channelStr = "";
        if (ValidateUtil.isNotNull(remitType)) {
            channelStr = " AND channel = '" + remitType + "' ";
        }

        String sql = " FROM user_wallet_pop uwp  " +
                " LEFT JOIN user_info ui ON ui.username = uwp.username  " +
                " LEFT JOIN city_postman cp ON cp.username = uwp.username " +
                " LEFT JOIN shop_info si ON si.ownUsername = uwp.username " +
                " WHERE  ui.delFlag = 0 AND uwp.delFlag = 0 AND si.delFlag = 0 AND uwp.popType = 7 " +
                userType + usernameStr + timeStr + remitTimeStr + doneStr + channelStr;

        try {
            StringBuffer sbCount = new StringBuffer();
            sbCount.append("select count(1) counts ");
            sbCount.append(sql);
            totalCount = UserDaoSql.getInstance().getCount(sbCount.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("查询失败，请稍后再试");
        }

        List<?> list = null;
        try {
            StringBuffer sbSql = new StringBuffer();
            sbSql.append("SELECT ui.name,ui.telPhone,uwp.*,si.ownName,si.shopName ");
            sbSql.append(sql);
            sbSql.append(" ORDER BY uwp.isDone ASC,uwp.createTime DESC ");
            if (isExcel != 1) {
                sbSql.append(" LIMIT ").append((page - 1) * size).append(",").append(size);
            }
            list = UserDaoSql.getInstance().queryBySql(sbSql.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("查询失败，请稍后再试");
        }

        if (ValidateUtil.isAbsList(list)) {

            if (isExcel == 1) {
                // 导出excel
//                String downloadUrl = generateOrderExcel(list);
//                if (ValidateUtil.isNotNull(downloadUrl)) {
//                    String url = SYS_CONFIG_PATH.IMAGE_BASE_URL + downloadUrl;
//                    return AjaxResult.successResult(url);
//                }
            }
            return AjaxResult.successResult(totalCount, list.size(), list);
        }
        return AjaxResult.successResult(0, 0, null);
    }

    //申请退回押金
    @RequestMapping(method = RequestMethod.POST, value = "/user/wallet/deposit/pop")
    @ResponseBody
    public String user_wallet_DEPOSIT_pop(String token, Double money, String channel) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNotAbsDouble(money)) {
            return AjaxResult.errorResult("请输入正确的金额");
        }

        UserWallet wallet = UserWalletMemory.getInstance().getWallet(user.getUsername());

        if (JYMathDoubleUtils.sub(wallet.getDepositMoney(), money) < 0) {
            return AjaxResult.errorResult("您的提现金额已超出余额");
        }
        if (ValidateUtil.isNull(channel)) {
            return AjaxResult.errorResult("请选择提现到位置");
        }
        ResultInfo resultInfo = moneyPopSave(user.getUsername(), user.getUserType(), user.getUsername(), wallet, money, channel, UserWalletMan.DEPOSIT_OUT, null, true, user.getUserType());

        // ResultInfo resultInfo = moneyPopSave(user.getUsername(), user.getUserType(), user.getUsername(), wallet, money, channel, UserWalletMan.DEPOSIT_OUT, null, true);
        if (null != resultInfo && !resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }

        return AjaxResult.successResult();
    }


    //获取充值记录
    @RequestMapping(method = RequestMethod.POST, value = "/user/wallet/in/history")
    @ResponseBody
    public String user_wallet_in_history(String token, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        List<UserWalletFlow> list = listOfIn(user.getUsername(), page, size);
        if (!ValidateUtil.isAbsList(list)) {
            return AjaxResult.successResult(0, null);
        }

        return AjaxResult.successResult(list.size(), list);
    }

    //获取需要交纳押金的金额
    @RequestMapping(method = RequestMethod.POST, value = "/user/wallet/deposit/get")
    @ResponseBody
    public String user_wallet_deposit_get(String token, Integer userType) {
//        //验证用户有效性
//        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
//        if (user == null) {
//            return AjaxResult.errorLogoutResult();
//        }

//        List<UserWalletPop> list = listOfPop(user.getUsername(), createTime, size);
//        if (!ValidateUtil.isAbsList(list)) {
//            return AjaxResult.successResult(0, null);
//        }

        if (null == userType) {//默认是店主类型
            userType = UserType.SHOP_OWNER;
        }
        Double money = SysConfigDepositMemory.getInstance().getByType(userType);
        if (null == money) {
            money = 0d;
        }

        return AjaxResult.successResult(money + "");
    }

    //押金充值记录
    @RequestMapping(method = RequestMethod.POST, value = "/user/wallet/deposit/history")
    @ResponseBody
    public String user_deposit_in_history(String token, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        List<UserWalletFlow> list = listOfDepositIn(user.getUsername(), page, size);
        if (!ValidateUtil.isAbsList(list)) {
            return AjaxResult.successResult(0, null);
        }

        return AjaxResult.successResult(list.size(), list);
    }

    //押金提现记录
    @RequestMapping(method = RequestMethod.POST, value = "/user/wallet/deposit/pop/history")
    @ResponseBody
    public String user_deposit_pop_history(String token, Long createTime, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        List<UserWalletPop> list = listOfDepositPop(user.getUsername(), createTime, size);
        if (!ValidateUtil.isAbsList(list)) {
            return AjaxResult.successResult(0, null);
        }

        return AjaxResult.successResult(list.size(), list);
    }


    //获取充值消费记录
    @RequestMapping(method = RequestMethod.POST, value = "/user/wallet/history")
    @ResponseBody
    public String user_wallet_history(String token, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (null == page) {
            page = 1;
        }
        if (null == size) {
            size = 20;
        }

        QueryCondition query = QueryCondition.getInstance();
        Expression expression = Expression.getInstance();
        expression.addChild("delFlag", 0);
        expression.addChild("username", user.getUsername());
        query.addCondition(expression);
        query.addOrders("createTime", "desc");
        query.setPage(page);
        query.setSize(size);

        String sql = DaoUtils.getSql(PojoTables.USER_WALLET_FLOW, query);
        List<UserWalletFlow> list = null;
        try {
            list = (List<UserWalletFlow>) UserDaoSql.getInstance().list(UserWalletFlow.class, sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if (!ValidateUtil.isAbsList(list)) {
            return AjaxResult.successResult(0, null);
        }

        return AjaxResult.successResult(list.size(), list);
    }

    //-----------------------商家

    //获取钱包余额
    @RequestMapping(method = RequestMethod.POST, value = "/shop/wallet")
    @ResponseBody
    public String shop_wallet(String token) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        UserWallet userWallet = getWallet(user.getUsername());

        return AjaxResult.successResult(userWallet);
    }

    //绑定支付渠道
    @RequestMapping(method = RequestMethod.POST, value = "/shop/wallet/bind")
    @ResponseBody
    public String shop_wallet_pop(String token,
                                  String alipay, String alipayRealName, String tenpay,
                                  String tenpayopenId, String tenpayRealName,
                                  String bankUserName, String bankName, String bankCard, String bankPhone) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        ResultInfo resultInfo = bindWallet(user, //店铺绑定支付渠道
                alipay, alipayRealName,
                tenpay, tenpayopenId, tenpayRealName,
                bankUserName, bankName, bankCard, bankPhone);
        if (null != resultInfo && !resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }

        return AjaxResult.successResult();
    }

    //提现申请
    @RequestMapping(method = RequestMethod.POST, value = "/shop/wallet/pop")
    @ResponseBody
    public String shop_wallet_pop(String token, Double money, String channel, String payPassword) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        // yangtk 提现支付密码验证
//        if (SYS_SETTINGS.VERIFY_PAYMENT_PASSWORD != null && 0 == 1 - SYS_SETTINGS.VERIFY_PAYMENT_PASSWORD) {
//            if (payPassword == null || "".equals(payPassword)) {
//                return AjaxResult.errorResult("请输入支付密码");
//            }
//
//            String getPayPassword = UserPwdMemory.getInstance().getPayPassword(user.getUsername());
//            if (payPassword == null || "".equals(payPassword)) {
//                return AjaxResult.errorResult("请先设置独立的支付密码");
//            }
//            // check
//            try {
//                payPassword = EncrypMD5.eccrypt(payPassword);
//            } catch (Exception e) {
//                e.printStackTrace();
//                return AjaxResult.errorResult("提现失败，请联系管理员");
//            }
//            if (!getPayPassword.equals(payPassword)) {
//                return AjaxResult.errorResult("支付密码错误，请重新输入");
//            }
//            // 验证密码成功 ：提现
//        }
        // end
        ResultInfo resultInfo = userWalletMoneyPopByUser(user, money, channel, true, UserType.SHOP_OWNER, payPassword);
        // ResultInfo resultInfo = moneyPop(user, money, channel, true);
        if (null != resultInfo && !resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }
        return AjaxResult.successResult();
    }

    //提现申请
    @RequestMapping(method = RequestMethod.POST, value = "/admin/shop/wallet/pop/by/shopId")
    @ResponseBody
    public String admin_shop_wallet_pop(String token, Double money, String channel, Long shopId, String payPassword) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        ShopInfo shop = ShopMemory.getInstance().getShopById(shopId);
        if (shop == null) {
            return AjaxResult.errorResult("未获取店铺信息");
        }
        UserInfo info = UserInfoMemory.getInstance().getUserInfo(shop.getOwnUsername());
        if (info == null) {
            return AjaxResult.errorResult("未获到用户信息");
        }
        // end
        ResultInfo resultInfo = userWalletMoneyPopByUser(info, money, channel, true, UserType.SHOP_OWNER, payPassword);
        if (null != resultInfo && !resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }
        return AjaxResult.successResult();
    }


    //查看自己的提现申请记录
    @RequestMapping(method = RequestMethod.POST, value = "/shop/wallet/pop/history")
    @ResponseBody
    public String shop_wallet_pop_history(String token, Long createTime, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        List<UserWalletPop> list = listOfPop(user.getUsername(), createTime, size);
        if (!ValidateUtil.isAbsList(list)) {
            return AjaxResult.successResult(0, null);
        }

        return AjaxResult.successResult(list.size(), list);
    }

    //根据时间获取自己的提现记录（分页）
    @RequestMapping(method = RequestMethod.POST, value = "/shop/wallet/pop/history/v2")
    @ResponseBody
    public String shop_wallet_pop_history_v2(String token, Long startTime, Long endTime, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }
        StringBuffer sql = new StringBuffer();
        sql.append(" select * from  ").append(PojoTables.USER_WALLET_POP)
                .append(" where delFlag = 0 and username='").append(user.getUsername()).append("' ")
                .append(" and popType = ").append(UserWalletMan.POP);
        if (ValidateUtil.isAbsLong(startTime)) {
            sql.append(" and createTime >=").append(startTime);
        }
        if (ValidateUtil.isAbsLong(endTime)) {
            sql.append(" and createTime <=").append(endTime);
        }
        sql.append(" order by id desc"); // 降序
        List<UserWalletPop> list = null;
        try {
            list = (List<UserWalletPop>) UserDaoSql.getInstance().list(UserWalletPop.class, sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("获取失败，请稍后重试");
        }
        if (ValidateUtil.isAbsList(list)) {
            JYPageUtils.PageList pageList = JYPageUtils.getList(list, page, size);
            return AjaxResult.successResult(pageList.totalCount, pageList.size, pageList.list);
        }
        return AjaxResult.successResult(0, 0, null);
    }

    // 用户获取自己提现记录
    @RequestMapping(method = RequestMethod.POST, value = "/user/wallet/pop/history/v2")
    @ResponseBody
    public String postman_wallet_pop_history_v2(String token, Long startTime, Long endTime, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }
        StringBuffer sql = new StringBuffer();
        sql.append(" select * from  ").append(PojoTables.USER_WALLET_POP)
                .append(" where delFlag = 0 and username='").append(user.getUsername()).append("' ")
                .append(" and popType = ").append(UserWalletMan.POP);
        if (ValidateUtil.isAbsLong(startTime)) {
            sql.append(" and createTime >=").append(startTime);
        }
        if (ValidateUtil.isAbsLong(endTime)) {
            sql.append(" and createTime <=").append(endTime);
        }
        sql.append(" order by id desc"); // 降序
        List<UserWalletPop> list = null;
        try {
            list = (List<UserWalletPop>) UserDaoSql.getInstance().list(UserWalletPop.class, sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("获取失败，请稍后重试");
        }
        if (ValidateUtil.isAbsList(list)) {
            JYPageUtils.PageList pageList = JYPageUtils.getList(list, page, size);
            return AjaxResult.successResult(pageList.totalCount, pageList.size, pageList.list);
        }
        return AjaxResult.successResult(0, 0, null);
    }

    //------------------------配送员
    //配送员钱包余额
    @RequestMapping(method = RequestMethod.POST, value = "/postman/wallet")
    @ResponseBody
    public String postman_wallet(String token) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        UserWallet userWallet = getWallet(user.getUsername());

        return AjaxResult.successResult(userWallet);
    }

    //配送员绑定支付渠道
    @RequestMapping(method = RequestMethod.POST, value = "/postman/wallet/bind")
    @ResponseBody
    public String postman_wallet_pop(String token,
                                     String alipay, String alipayRealName,
                                     String tenpay, String tenpayopenId, String tenpayRealName,
                                     String bankUserName, String bankName, String bankCard, String bankPhone) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        ResultInfo resultInfo = bindWallet(user,//配送员绑定
                alipay, alipayRealName,
                tenpay, tenpayopenId, tenpayRealName,
                bankUserName, bankName, bankCard, bankPhone);
        if (null != resultInfo && !resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }

        return AjaxResult.successResult();
    }


    //配送员提现申请
    @RequestMapping(method = RequestMethod.POST, value = "/postman/wallet/pop")
    @ResponseBody
    public String postman_wallet_pop(String token, Double money, String channel, Long companyId, String payPassword) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        // yangtk 提现支付密码验证
        if (SYS_SETTINGS.VERIFY_PAYMENT_PASSWORD != null && 0 == 1 - SYS_SETTINGS.VERIFY_PAYMENT_PASSWORD) {
            if (payPassword == null || "".equals(payPassword)) {
                return AjaxResult.errorResult("请输入支付密码");
            }

            String getPayPassword = UserPwdMemory.getInstance().getPayPassword(user.getUsername());
            if (getPayPassword == null || "".equals(getPayPassword)) {
                return AjaxResult.errorResult("请先设置独立的支付密码");
            }
            // check
            try {
                payPassword = EncrypMD5.eccrypt(payPassword);
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.errorResult("提现失败，请联系管理员");
            }
            if (!getPayPassword.equals(payPassword)) {
                return AjaxResult.errorResult("支付密码错误，请重新输入");
            }
            // 验证密码成功 ：提现
        }
        // end

        if (SYS_SETTINGS.CUSTOM_SYSTEM_TYPE == 1) {
            if (companyId == null) {
                return AjaxResult.errorResult("公司id为空");
            }
            // 查看是都签约
            List<PostmanSignCompanyInfo> companyInfos = PostmanSignCompanyMemory.getInstance().listOfPostman(user.getUsername(), companyId, null, PostmanSignCompanyInfo.POSTMAN_COMPANY_SIGN_STATUS_AGREE);
            if (companyInfos == null || companyInfos.size() == 0) {
                return AjaxResult.errorResult("公司尚未未签约");
            }
            ResultInfo resultInfo = postmanMoneyCompanyPop(user, companyId, money, channel, true);
            if (null != resultInfo && !resultInfo.isSuccess()) {
                return AjaxResult.errorResult(resultInfo.getError());
            }
        } else {
            ResultInfo resultInfo = moneyPop(user, money, channel, true, UserType.POSTMAN);
            // ResultInfo resultInfo = moneyPop(user, money, channel, true);
            if (null != resultInfo && !resultInfo.isSuccess()) {
                return AjaxResult.errorResult(resultInfo.getError());
            }
        }
        return AjaxResult.successResult();
    }


    //配送员查看自己的提现申请记录
    @RequestMapping(method = RequestMethod.POST, value = "/postman/wallet/pop/history")
    @ResponseBody
    public String postman_wallet_pop_history(String token, Long createTime, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        List<UserWalletPop> list = listOfPop(user.getUsername(), createTime, size);
        if (ValidateUtil.isAbsList(list)) {
            // 一乙项目提现需要配送公司
            if (SYS_SETTINGS.CUSTOM_SYSTEM_TYPE == 1) {
                List<UserWalletPopVO> walletPopVOS = list.stream().map(a -> a.convert2VO()).collect(Collectors.toList());
                return AjaxResult.successResult(walletPopVOS.size(), walletPopVOS);
            }
            return AjaxResult.successResult(list.size(), list);
        }

        return AjaxResult.successResult(0, null);
    }


    //--------------------管理员
    //查询所有的提现申请记录
    @RequestMapping(method = RequestMethod.POST, value = "/admin/shop/pop/history")
    @ResponseBody
    public String user_wallet_pop_history_admin(String token,
                                                String username, // 店铺（申请人）
                                                Integer isDone,
                                                Long startTime, Long endTime,   // 申请提现时间
                                                String city,      // 地区
                                                Long remitStatTime, Long remitEndTime, // 打款时间
                                                String remitType, // 打款渠道
                                                String cityAdmin,// 代理
                                                Long agentId, // 商圈
                                                Integer isExcel,    // 是否导出Excel
                                                Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //验证是否有登录权限
        if (!User.getInstance().hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        if (null == isExcel) {
            isExcel = 0;
        }
        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }
        Long totalCount = 0l;
        if ((user.getUserType() == UserType.ADMIN || SysCityCompanyMan.isAdminCompanyUser(user.getUsername()))) {
            cityAdmin = SysCityCompanyMan.getSysCompanyOwnUsername(user.getUsername());
        }
        String timeStr = "";
        if (null != startTime && null != endTime) {
            timeStr = " and a.createTime >= " + startTime + " and a.createTime <= " + endTime + " ";
        }
//        if (null != endTime) {
//            timeStr = " and a.createTime <= " + endTime;
//        }

        StringBuffer sb = new StringBuffer();
        sb.append(" FROM ").append(PojoTables.USER_WALLET_POP).append(" a ")
                .append(" left join ")
                .append(" (SELECT s1.ownUsername,s2.id FROM (SELECT id FROM  ")
                .append(PojoTables.ShopInfo).append("  GROUP BY ownUsername) AS s2  LEFT JOIN ")
                .append(PojoTables.ShopInfo).append(" s1 ON s2.id = s1.id) ")
                .append(" b on a.username = b.ownUsername ");
        if (ValidateUtil.isNotNull(cityAdmin)) {
            sb.append(" LEFT JOIN ( ")
                    .append(" SELECT c.shopId FROM ").append(PojoTables.SHOP_AGENT_RELATION).append(" c")
                    .append(" LEFT JOIN ").append(PojoTables.USER_AGENT_RELATION).append(" d on c.agentId = d.agentId")
                    .append(" WHERE c.delFlag = 0 AND d.delFlag = 0 AND d.username = '").append(cityAdmin).append("'")
                    .append(" ) e ON e.shopId = b.id");
        }
        if (null != agentId) {
            sb.append(" left join ").append(PojoTables.SHOP_AGENT_RELATION).append(" sar on sar.shopId=b.id and sar.delFlag=0 ");
        }

//        sb.append(" where b.id is not null and b.delFlag = 0 and a.delFlag =0 ").append(timeStr).append(ValidateUtil.isNotNull(cityAdmin) ? " AND e.shopId IS NOT NULL" : " ");
        sb.append(" where b.id is not null and a.delFlag =0 ").append(timeStr).append(ValidateUtil.isNotNull(cityAdmin) ? " AND e.shopId IS NOT NULL" : " ");
        sb.append(" and (a.userPopType is null or a.userPopType = ").append(UserType.SHOP_OWNER).append(")");
        //isDone  0所有 1已提现  2所有未提现
        if (ValidateUtil.isAbsInteger(isDone) && isDone > 0) {
            if (0 == 2 - isDone) {
                sb.append(" and a.isDone=0 ");
            } else {
                sb.append(" and a.isDone=1 ");
            }
        }
        if (ValidateUtil.isNotNull(username)) { //
            sb.append(" and a.username='").append(username).append("'");
        }
        if (null != agentId) { //
            sb.append(" and sar.agentId=").append(agentId).append(" ");
        }
        if (ValidateUtil.isNotNull(city)) {
            sb.append(" and b.city ='").append(city).append("'");
        }

        if (null != remitStatTime && null != remitEndTime) {
            sb.append(" and a.popTime >=" + remitStatTime + " && a.popTime <=" + remitEndTime);
        }

        if (ValidateUtil.isNotNull(remitType)) {
            sb.append(" and a.channel = '" + remitType).append("'");
        }


        try {
            StringBuffer sbCount = new StringBuffer();
            // sbCount.append("select count(1) counts ");
            sbCount.append("select count(DISTINCT a.id) counts ");
            sbCount.append(sb.toString());
            totalCount = UserDaoSql.getInstance().getCount(sbCount.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("查询失败，请稍后再试");
        }

        List<?> list = null;
        try {
            StringBuffer sbSql = new StringBuffer();
            sbSql.append("SELECT DISTINCT a.* ");
            sbSql.append(sb.toString());
            sbSql.append(" ORDER BY isDone ASC,a.createTime DESC ");
            if (isExcel != 1) {
                sbSql.append(" LIMIT ").append((page - 1) * size).append(",").append(size);
            }
            list = UserDaoSql.getInstance().list(UserWalletPop.class, sbSql.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("查询失败，请稍后再试");
        }

        //        QueryCondition query = QueryCondition.getInstance();
        //        Expression expression = Expression.getInstance();
        //        expression.addChild("delFlag", 0);
        //        if (ValidateUtil.isNotNull(username)) {
        //            expression.addChild("username", username);
        //        }
        //        //isDone  0所有 1已提现  2所有未提现
        //        if (ValidateUtil.isAbsInteger(isDone) && isDone > 0) {
        //            if (0 == 2 - isDone) {
        //                expression.addChild("isDone", 0);
        //            } else {
        //                expression.addChild("isDone", 1);
        //            }
        //        }
        //
        //        query.addCondition(expression);//所有未删除的店铺
        //        query.setPage(page);
        //        query.setSize(size);
        //
        //        String sql = DaoUtils.getSql(PojoTables.USER_WALLET_POP, query);
        //        String sqlCount = DaoUtils.getSqlCount(PojoTables.USER_WALLET_POP, query);
        //        List<UserWalletPop> list = null;
        ////        Long totalCount = 0l;
        //        System.out.println(sql);
        //        try {
        //            list = (List<UserWalletPop>) UserDaoSql.getInstance().list(UserWalletPop.class, sql);
        //            totalCount = UserDaoSql.getInstance().getCount(sqlCount);
        //        } catch (SQLException e) {
        //            e.printStackTrace();
        //        }

        if (ValidateUtil.isAbsList(list)) {
            List<UserWalletPop> resultList = new ArrayList<UserWalletPop>();
            List<UserWalletPop> needQuery = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                UserWalletPop userWalletPop = (UserWalletPop) list.get(i);
                if (null == userWalletPop) {
                    continue;
                }
                if (ValidateUtil.isID(userWalletPop.getShopId())) {
                    ShopInfo shopInfo = ShopMemory.getInstance().getShopById(userWalletPop.getShopId());
                    if (null == shopInfo) {
                        needQuery.add(userWalletPop);
                    } else {
                        ShopInfoVO shopInfoVO = new ShopInfoVO();
                        try {
                            ObjectUtils.copyPropertiesExclude(shopInfo, shopInfoVO, null);
                        } catch (Exception e) {
                            e.printStackTrace();
                            continue;
                        }
                        if (ValidateUtil.isNotNull(shopInfoVO.getImageUrl()) && ValidateUtil.isNotNetUrl(shopInfoVO.getImageUrl())) {
                            String thumb = ImageService.getThumbnailImgUrl(shopInfoVO.getImageUrl(), shopInfo.getImgUpVer(), shopInfo.getThumbnailState());
                            shopInfoVO.setImageThumbnailUrl(thumb);
//                            shopInfoVO.setImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + shopInfoVO.getImageUrl());
                            shopInfoVO.setImageUrl(ImageService.getImgUrl(shopInfo.getImgUpVer()) + shopInfoVO.getImageUrl());
                        }
                        userWalletPop.setShopInfo(shopInfoVO);
                    }
                }
                resultList.add(userWalletPop);
            }
            if (needQuery.size() > 0) {
                Set<Long> set = needQuery.stream().map(bean -> bean.getShopId()).collect(Collectors.toSet());
                Map<Long, ShopInfo> map = getShopInfo(set);
                if (map != null) {
                    for (UserWalletPop pop : needQuery) {
                        if (pop.getShopId() != null) {
                            ShopInfo info = map.get(pop.getShopId());
                            if (info != null) {
                                ShopInfoVO shopInfoVO = new ShopInfoVO();
                                try {
                                    ObjectUtils.copyPropertiesExclude(info, shopInfoVO, null);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    continue;
                                }
                                if (ValidateUtil.isNotNull(shopInfoVO.getImageUrl()) && ValidateUtil.isNotNetUrl(shopInfoVO.getImageUrl())) {
                                    String thumb = ImageService.getThumbnailImgUrl(shopInfoVO.getImageUrl(), info.getImgUpVer(), info.getThumbnailState());
                                    shopInfoVO.setImageThumbnailUrl(thumb);
//                                    shopInfoVO.setImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + shopInfoVO.getImageUrl());
                                    shopInfoVO.setImageUrl(ImageService.getImgUrl(info.getImgUpVer()) + shopInfoVO.getImageUrl());
                                }
                                UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(pop.getUsername());
                                if (userInfo != null) {
                                    UserInfoVO vo = new UserInfoVO();
                                    BeanUtils.copyProperties(userInfo, vo);
                                    pop.setUserInfo(vo);
                                }
                                pop.setShopInfo(shopInfoVO);
                            }
                        }
                    }
                }
            }
            // 过滤没有店铺的
            if (ValidateUtil.isAbsList(resultList)) {
                resultList = resultList.stream().filter(bean -> ValidateUtil.isID(bean.getShopId()) && bean.getShopInfo() != null).collect(Collectors.toList());
            }
            if (ValidateUtil.isAbsList(resultList)) {
                if (isExcel == 1) {
                    // 导出excel
                    String downloadUrl = generateOrderExcel(resultList);
                    if (ValidateUtil.isNotNull(downloadUrl)) {
                        if (ValidateUtil.isNotNetUrl(downloadUrl)) {
                            downloadUrl = SYS_CONFIG_PATH.IMAGE_BASE_URL + downloadUrl;
                        }
                        return AjaxResult.successResult(downloadUrl);
                    }
                }
                return AjaxResult.successResult(totalCount, resultList.size(), resultList);
            }
        }
        return AjaxResult.successResult(0, 0, null);
    }


    private Map<Long, ShopInfo> getShopInfo(Set<Long> set) {
        if (set == null || set.isEmpty()) {
            return null;
        }
        StringBuilder sql = new StringBuilder();
        sql.append("select * from ").append(PojoTables.ShopInfo)
                .append(" where id  in (").append(StringUtils.join(set, ",")).append(")");
        List<ShopInfo> list = null;
        try {
            list = (List<ShopInfo>) UserDaoSql.getInstance().list(ShopInfo.class, sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        if (list != null && list.size() > 0) {
            return list.stream().collect(Collectors.toMap(ShopInfo::getId, Function.identity()));
        }
        return null;
    }


    //---------------------------------生成店铺提现Excel
    private String generateOrderExcel(List<UserWalletPop> list) {
        if (!ValidateUtil.isAbsList(list)) {
            return null;
        }
        String outputPath = "";
        try {
//        String basePath = Common.proImgPath;
//            String basePath = "D:\\nginx-1.13.5\\html\\dw5fz\\wallet\\pop";
//            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMM");
//            Date date = new Date(System.currentTimeMillis());
//            String fileHash = formatter.format(date);

//        String templatePath = basePath + File.separator + "a.xls";
            outputPath = SYS_CONFIG_PATH.ORDER_IMAGE + "/" + DateUtils.getCurrentYearMonth() + "/" + DateUtils.getCurrTime() + ".xls";

//        File templateFile = new File(templatePath);
            File outputFile = new File(SYS_CONFIG_PATH.IMAGE_BASE_FILE + outputPath);
            FileUtils.forceMkdirParent(outputFile);

            WritableWorkbook workbook = Workbook.createWorkbook(outputFile);

//        workbook = Workbook.createWorkbook(outputFile, Workbook.getWorkbook(templateFile));

            // 生成名为"学生"的工作表，参数0表示这是第一页
            WritableSheet sheet = workbook.createSheet("sheet1", 0);

//        WritableSheet sheet = workbook.getSheet(0);
            jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#0.00");   // 设置数字格式
            jxl.write.WritableCellFormat wcfN = new jxl.write.WritableCellFormat(nf); // 设置表单格式
            int col = 0;   // 列
            int row = 0;  // 行
            sheet.addCell(new Label(col++, row, "商家名称"));
            sheet.addCell(new Label(col++, row, "商家电话"));
            sheet.addCell(new Label(col++, row, "商家地址"));
            sheet.addCell(new Label(col++, row, "打款账号"));
//            sheet.addCell(new Label(col++, row, "打款姓名"));
//            sheet.addCell(new Label(col++, row, "打款手机号"));
            sheet.addCell(new Label(col++, row, "打款金额"));
            sheet.addCell(new Label(col++, row, "打款渠道"));
            sheet.addCell(new Label(col++, row, "支付宝账号"));
            sheet.addCell(new Label(col++, row, "微信账号"));
            sheet.addCell(new Label(col++, row, "开户行"));
            sheet.addCell(new Label(col++, row, "开户行姓名"));
            sheet.addCell(new Label(col++, row, "银行卡号"));
            sheet.addCell(new Label(col++, row, "申请时间"));
            sheet.addCell(new Label(col++, row, "确认打款时间"));
            sheet.addCell(new Label(col++, row, "操作人"));
            row = 1;
            for (UserWalletPop record : list) {
                col = 0;
                double totalPrice = 0;

//                if (record.getIsPaid() == 1) {
//                    totalPrice = record.getTotalPrice();
//                }
                String channel = "";
                if (null != record.getChannel()) {
                    if (record.getChannel().equals("alipay")) {
                        channel = "支付宝";
                    } else if (record.getChannel().equals("wx")) {
                        channel = "微信";
                    } else if (record.getChannel().equals("bankCard")) {
                        channel = "银行卡";
                    }
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                String createTime = sdf.format(record.getCreateTime()); // 申请时间
                String popTime = sdf.format(record.getPopTime()); // 申请时间

                sheet.addCell(new Label(col++, row, record.getShopInfo().getShopName()));
                sheet.addCell(new Label(col++, row, record.getShopInfo().getTelephone()));
                sheet.addCell(new Label(col++, row, record.getShopInfo().getAddress()));
                sheet.addCell(new Label(col++, row, record.getUsername()));
                sheet.addCell(new Number(col++, row, record.getMoney()));
                sheet.addCell(new Label(col++, row, channel));
                sheet.addCell(new Label(col++, row, record.getAlipay()));
                sheet.addCell(new Label(col++, row, record.getTenpay()));
                sheet.addCell(new Label(col++, row, record.getBankName()));
                sheet.addCell(new Label(col++, row, record.getBankUserName()));
                sheet.addCell(new Label(col++, row, record.getBankCard()));
                sheet.addCell(new Label(col++, row, createTime));
                sheet.addCell(new Label(col++, row, popTime));
                sheet.addCell(new Label(col++, row, record.getUpdateUser()));
                row++;     // 行
            }

            workbook.write();
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            outputPath = JYFileUtils.saveFile2Oss(outputPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return outputPath;
    }

    //--------------------管理员
    //查询所有的提现申请记录
    @RequestMapping(method = RequestMethod.POST, value = "/admin/cityAdmin/pop/history")
    @ResponseBody
    public String user_wallet_pop_history_cityAdmin(String token, String username, Integer isExcel, Integer isDone, Long startTime, Long endTime, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //验证是否有登录权限
        if (!User.getInstance().hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }
        Long totalCount = 0l;

        if (null == isExcel) {
            isExcel = 0;
        }
        String timeStr = "";
        if (null != startTime) {
            timeStr = " and a.createTime >= " + startTime;
        }
        if (null != endTime) {
            timeStr = " and a.createTime <= " + endTime;
        }

        StringBuffer sb = new StringBuffer();
        sb.append(" FROM ").append(PojoTables.USER_WALLET_POP).append(" a ")
                .append(" left join ").append(PojoTables.SysCityAdmin).append(" b on a.username = b.username ")
                .append(" where b.id is not null  and a.delFlag =0 ").append(timeStr);
        //isDone  0所有 1已提现  2所有未提现
        if (ValidateUtil.isAbsInteger(isDone) && isDone > 0) {
            if (0 == 3 - isDone) {
                // 被拒绝
                sb.append(" and a.isDone=2 ");
            } else if (0 == 2 - isDone) {
                sb.append(" and a.isDone=0 ");
            } else {
                sb.append(" and a.isDone=1 ");
            }
        }
        if (ValidateUtil.isNotNull(username)) {
            sb.append(" and a.username like '%").append(username).append("%' ");
        }
        try {
            StringBuffer sbCount = new StringBuffer();
            sbCount.append("select count(1) counts ");
            sbCount.append(sb.toString());
            totalCount = UserDaoSql.getInstance().getCount(sbCount.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("查询失败，请稍后再试");
        }

        List<?> list = null;
        try {
            StringBuffer sbSql = new StringBuffer();
            sbSql.append("SELECT a.* ");
            sbSql.append(sb.toString());
            sbSql.append(" ORDER BY isDone ASC,a.createTime DESC ");
            if (isExcel != 1) {
                sbSql.append(" LIMIT ").append((page - 1) * size).append(",").append(size);
            }
            list = UserDaoSql.getInstance().list(UserWalletPopVO.class, sbSql.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("查询失败，请稍后再试");
        }

        if (ValidateUtil.isAbsList(list)) {

            List<UserWalletPopVO> voList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                UserWalletPopVO vo = (UserWalletPopVO) list.get(i);
                if (null == vo) {
                    continue;
                }
                if (ValidateUtil.isNotNull(vo.getUsername())) {
                    UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(vo.getUsername());
                    if (null != userInfo) {
                        vo.setName(userInfo.getName());
                        if (ValidateUtil.isNotNull(userInfo.getSignPhoto())) {
                            if (ValidateUtil.isNotNetUrl(userInfo.getSignPhoto())) {
                                vo.setUserImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + userInfo.getSignPhoto());
                            } else {
                                vo.setUserImageUrl(userInfo.getSignPhoto());
                            }
                        }
                        vo.setName(userInfo.getName());
                        vo.setTelPhone(userInfo.getTelPhone());
                        UserInfoVO userInfoVO = new UserInfoVO();
                        BeanUtils.copyProperties(userInfo, userInfoVO);
                        vo.setUserInfo(userInfoVO);
                    }
                }
                voList.add(vo);
            }
            if (ValidateUtil.isAbsList(voList)) {
                if (isExcel == 1) {
                    // 导出excel
                    String downloadUrl = agentWalletExcel(voList);
                    if (ValidateUtil.isNotNull(downloadUrl)) {
                        if (ValidateUtil.isNotNetUrl(downloadUrl)) {
                            downloadUrl = SYS_CONFIG_PATH.IMAGE_BASE_URL + downloadUrl;
                        }
                        return AjaxResult.successResult(downloadUrl);
                    }
                }
                return AjaxResult.successResult(totalCount, voList.size(), voList);
            }
        }
        return AjaxResult.successResult(0, 0, null);
    }

    //---------------------------------生成代理提现Excel
    private String agentWalletExcel(List<UserWalletPopVO> list) {
        if (!ValidateUtil.isAbsList(list)) {
            return null;
        }
        String outputPath = "";
        try {
            outputPath = SYS_CONFIG_PATH.ORDER_IMAGE + "/" + DateUtils.getCurrentYearMonth() + "/" + DateUtils.getCurrTime() + ".xls";

            File outputFile = new File(SYS_CONFIG_PATH.IMAGE_BASE_FILE + outputPath);
            FileUtils.forceMkdirParent(outputFile);

            WritableWorkbook workbook = Workbook.createWorkbook(outputFile);

//        workbook = Workbook.createWorkbook(outputFile, Workbook.getWorkbook(templateFile));

            // 生成名为"学生"的工作表，参数0表示这是第一页
            WritableSheet sheet = workbook.createSheet("sheet1", 0);

//        WritableSheet sheet = workbook.getSheet(0);
            jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#0.00");   // 设置数字格式
            jxl.write.WritableCellFormat wcfN = new jxl.write.WritableCellFormat(nf); // 设置表单格式
            int col = 0;   // 列
            int row = 0;  // 行
            sheet.addCell(new Label(col++, row, "申请人"));
            sheet.addCell(new Label(col++, row, "本次提现金额"));
            sheet.addCell(new Label(col++, row, "提现后金额"));
            sheet.addCell(new Label(col++, row, "提现渠道"));
            sheet.addCell(new Label(col++, row, "支付宝账号"));
            sheet.addCell(new Label(col++, row, "微信账号"));
            sheet.addCell(new Label(col++, row, "开户行"));
            sheet.addCell(new Label(col++, row, "开户行姓名"));
            sheet.addCell(new Label(col++, row, "银行卡号"));
            sheet.addCell(new Label(col++, row, "提现状态"));
            sheet.addCell(new Label(col++, row, "拒绝原因"));
            sheet.addCell(new Label(col++, row, "申请时间"));
            sheet.addCell(new Label(col++, row, "审批时间"));
            row = 1;
            for (UserWalletPopVO record : list) {
                col = 0;
                double totalPrice = 0;

//                if (record.getIsPaid() == 1) {
//                    totalPrice = record.getTotalPrice();
//                }
                String channel = "";
                if (null != record.getChannel()) {
                    if (record.getChannel().equals("alipay")) {
                        channel = "支付宝";
                    } else if (record.getChannel().equals("wx")) {
                        channel = "微信";
                    } else if (record.getChannel().equals("bankCard")) {
                        channel = "银行卡";
                    }
                }
                String status = "";
                if (null != record.getChannel()) {
                    if (record.getIsDone() == 0) {
                        status = "申请中";
                    } else if (record.getIsDone() == 1) {
                        status = "成功";
                    } else if (record.getIsDone() == 2) {
                        status = "被拒绝";
                    }
                }

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                String createTime = sdf.format(record.getCreateTime()); // 申请时间
                String popTime = sdf.format(record.getPopTime()); // 申请时间

                sheet.addCell(new Label(col++, row, record.getName()));
                sheet.addCell(new Number(col++, row, record.getMoney()));
                sheet.addCell(new Label(col++, row, channel));
                sheet.addCell(new Label(col++, row, record.getAlipay()));
                sheet.addCell(new Label(col++, row, record.getTenpay()));
                sheet.addCell(new Label(col++, row, record.getBankName()));
                sheet.addCell(new Label(col++, row, record.getBankUserName()));
                sheet.addCell(new Label(col++, row, record.getBankCard()));
                sheet.addCell(new Label(col++, row, status));
                sheet.addCell(new Label(col++, row, record.getExtra1()));
                sheet.addCell(new Label(col++, row, createTime));
                sheet.addCell(new Label(col++, row, popTime));
                row++;     // 行
            }

            workbook.write();
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            outputPath = JYFileUtils.saveFile2Oss(outputPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return outputPath;
    }

    // 查询所有的提现申请记录总金额
    @RequestMapping(method = RequestMethod.POST, value = "/admin/shop/pop/history/total")
    @ResponseBody
    public String user_wallet_pop_total_admin(String token, String username, Integer isDone, Long startTime, Long endTime) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //验证是否有登录权限
        if (!User.getInstance().hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        Long totalCount = 0l;

        String timeStr = "";
        if (null != startTime) {
            timeStr = " and a.createTime >= " + startTime;
        }
        if (null != endTime) {
            timeStr = " and a.createTime <= " + endTime;
        }

        StringBuffer sb = new StringBuffer();
        sb.append(" FROM ").append(PojoTables.USER_WALLET_POP).append(" a ")
                .append(" left join ").append(PojoTables.ShopInfo).append(" b on a.username = b.ownUsername ")
                .append(" where b.id is not null and b.delFlag = 0 and a.delFlag =0 ").append(timeStr);
        //isDone  0所有 1已提现  2所有未提现
        if (ValidateUtil.isAbsInteger(isDone) && isDone > 0) {
            if (0 == 2 - isDone) {
                sb.append(" and a.isDone=0 ");
            } else {
                sb.append(" and a.isDone=1 ");
            }
        }
        if (ValidateUtil.isNotNull(username)) {
            sb.append(" and a.username='").append(username).append("'");
        }
        try {
            StringBuffer sbCount = new StringBuffer();
            sbCount.append(" select  IFNULL(T.totalMoney,0) totalMoney FROM  (");
            sbCount.append("select SUM(IFNULL(money,0)) totalMoney ");
            sbCount.append(sb.toString()).append(" ) T");
            HashMap<String, Object> hashMap = UserDaoSql.getInstance().queryMapBySql(sbCount.toString());
            Object obj = hashMap.get("totalMoney");
            if (obj != null) {
                Double totalMoney = Double.parseDouble(obj.toString());
                return "{\"status\":1,\"info\":{\"totalMoney\":" + totalMoney + "}}";
            } else {
                return AjaxResult.errorResult("查询失败，请稍后再试");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("查询失败，请稍后再试");
        }
    }

    //查询所有的提现申请记录
    @RequestMapping(method = RequestMethod.POST, value = "/admin/wallet/pop/history")
    @ResponseBody
    public String wallet_pop_history_admin(String token, String username, Integer popType, Long startTime, Long endTime, Integer isDone, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //验证是否有登录权限
        if (!User.getInstance().hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (null == page) {
            page = 1;
        }
        if (null == size) {
            size = 20;
        }


        QueryCondition query = QueryCondition.getInstance();
        Expression expression = Expression.getInstance();
        expression.addChild("delFlag", 0);
        if (ValidateUtil.isNotNull(username)) {
            expression.addChild("username", "like", username);
        }
        if (null != isDone) {
            //isDone  0所有 1已提现  2所有未提现
            if (0 == 3 - isDone) {
                // 被拒绝
                expression.addChild("isDone", 2);
            } else if (0 == 2 - isDone) {
                expression.addChild("isDone", 0);
            } else if (0 == 1 - isDone) {
                expression.addChild("isDone", 1);
            }

        }
        if (null != popType) {
            // 2余额提现 7押金提现 8扣除押金
            expression.addChild("popType", popType);
        }

        if (null != startTime) {
            expression.addChild("createTime", ">=", startTime);
        }
        if (null != endTime) {
            expression.addChild("createTime", "<=", endTime);
        }

        query.addCondition(expression);
        query.setPage(page);
        query.setSize(size);
        String sql = DaoUtils.getSql(PojoTables.USER_WALLET_POP, query);
        String sqlCount = DaoUtils.getSqlCount(PojoTables.USER_WALLET_POP, query);
        List<UserWalletPop> list = null;
        Long totalCount = 0l;
        try {
            list = (List<UserWalletPop>) UserDaoSql.getInstance().list(UserWalletPop.class, sql);
            totalCount = UserDaoSql.getInstance().getCount(sqlCount);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if (ValidateUtil.isAbsList(list)) {
            List<UserWalletPopVO> voList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                UserWalletPop userWalletPop = (UserWalletPop) list.get(i);
                if (null == userWalletPop) {
                    continue;
                }

                if (0 == UserType.SHOP_OWNER - userWalletPop.getUserType()) {
                    ShopInfo shopInfo = ShopMemory.getInstance().getShopById(userWalletPop.getShopId());
                    if (null == shopInfo) {
                        continue;
                    }
                    ShopInfoVO shopInfoVO = new ShopInfoVO();
                    try {
                        ObjectUtils.copyPropertiesExclude(shopInfo, shopInfoVO, null);
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }
                    userWalletPop.setShopInfo(shopInfoVO);
                }
                UserWalletPopVO vo = new UserWalletPopVO();
                try {
                    ObjectUtils.copyPropertiesExclude(userWalletPop, vo, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                if (ValidateUtil.isNotNull(vo.getUsername())) {
                    UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(vo.getUsername());
                    if (null != userInfo) {
                        vo.setName(userInfo.getName());
                        if (ValidateUtil.isNotNull(userInfo.getSignPhoto())) {
                            if (ValidateUtil.isNotNetUrl(userInfo.getSignPhoto())) {
                                vo.setUserImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + userInfo.getSignPhoto());
                            } else {
                                vo.setUserImageUrl(userInfo.getSignPhoto());
                            }
                        }
                        vo.setName(userInfo.getName());
                        vo.setTelPhone(userInfo.getTelPhone());
                    }
                }
                voList.add(vo);
            }

            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(totalCount, voList.size(), voList);
            }

        }
        return AjaxResult.successResult(0, 0, null);

//
//        Long totalCount = 0l;
//
//
//        StringBuffer sb = new StringBuffer();
//        sb.append(" FROM ").append(PojoTables.USER_WALLET_POP).append(" a ")
//                .append(" left join ").append(PojoTables.ShopInfo).append(" b on a.username = b.ownUsername ")
//                .append(" where b.id is not null and b.delFlag = 0 and a.delFlag =0 ");
//        //isDone  0所有 1已提现  2所有未提现
//        if (ValidateUtil.isAbsInteger(isDone) && isDone > 0) {
//            if (0 == 2 - isDone) {
//                sb.append(" and a.isDone=0 ");
//            } else {
//                sb.append(" and a.isDone=1 ");
//            }
//        }
//        if (ValidateUtil.isNotNull(username)) {
//            sb.append(" and a.username='").append(username).append("'");
//        }
//
//
//        try {
//            StringBuffer sbCount = new StringBuffer();
//            sbCount.append("select count(1) counts ");
//            sbCount.append(sb.toString());
//            totalCount = UserDaoSql.getInstance().getCount(sbCount.toString());
//        } catch (SQLException e) {
//            e.printStackTrace();
//            return AjaxResult.errorResult("查询失败，请稍后再试");
//        }
//
//        List<?> list = null;
//        try {
//            StringBuffer sbSql = new StringBuffer();
//            sbSql.append("SELECT a.* ");
//            sbSql.append(sb.toString());
//            sbSql.append(" LIMIT ").append((page - 1) * size).append(",").append(size);
//            list = UserDaoSql.getInstance().list(UserWalletPop.class, sbSql.toString());
//        } catch (SQLException e) {
//            e.printStackTrace();
//            return AjaxResult.errorResult("查询失败，请稍后再试");
//        }
//
////        QueryCondition query = QueryCondition.getInstance();
////        Expression expression = Expression.getInstance();
////        expression.addChild("delFlag", 0);
////        if (ValidateUtil.isNotNull(username)) {
////            expression.addChild("username", username);
////        }
////        //isDone  0所有 1已提现  2所有未提现
////        if (ValidateUtil.isAbsInteger(isDone) && isDone > 0) {
////            if (0 == 2 - isDone) {
////                expression.addChild("isDone", 0);
////            } else {
////                expression.addChild("isDone", 1);
////            }
////        }
////
////        query.addCondition(expression);//所有未删除的店铺
////        query.setPage(page);
////        query.setSize(size);
////
////        String sql = DaoUtils.getSql(PojoTables.USER_WALLET_POP, query);
////        String sqlCount = DaoUtils.getSqlCount(PojoTables.USER_WALLET_POP, query);
////        List<UserWalletPop> list = null;
//////        Long totalCount = 0l;
////        System.out.println(sql);
////        try {
////            list = (List<UserWalletPop>) UserDaoSql.getInstance().list(UserWalletPop.class, sql);
////            totalCount = UserDaoSql.getInstance().getCount(sqlCount);
////        } catch (SQLException e) {
////            e.printStackTrace();
////        }
//
//        if (ValidateUtil.isAbsList(list)) {
//            List<UserWalletPop> resultList = new ArrayList<UserWalletPop>();
//            for (int i = 0; i < list.size(); i++) {
//                UserWalletPop userWalletPop = (UserWalletPop) list.get(i);
//                if (null == userWalletPop) {
//                    continue;
//                }
//
//                if (UserType.SHOP_OWNER == userWalletPop.getUserType()) {
//                    ShopInfo shopInfo = ShopMemory.getInstance().getShopById(userWalletPop.getShopId());
//                    if (null == shopInfo) {
//                        continue;
//                    }
//                    ShopInfoVO shopInfoVO = new ShopInfoVO();
//                    try {
//                        ObjectUtils.copyPropertiesExclude(shopInfo, shopInfoVO, null);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                        continue;
//                    }
//                    userWalletPop.setShopInfo(shopInfoVO);
//                }
//
//                resultList.add(userWalletPop);
//            }
//
//            if (ValidateUtil.isAbsList(resultList)) {
//                return AjaxResult.successResult(totalCount, resultList.size(), resultList);
//            }
//
//        }


//        return AjaxResult.successResult(0, 0, null);
    }


    //管理员设置为已提现
    @RequestMapping(method = RequestMethod.POST, value = "/admin/shop/pop/done")
    @ResponseBody
    public String user_wallet_pop_done_admin(String token, String username, Long id, Double actualTransferMoney, Integer isAutoPopDone, String note, FileUploadInfo uploadInfo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //验证是否有登录权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (ValidateUtil.isNotID(id)) {
            return AjaxResult.errorResult("请选择需要为已提现的记录");
        }
        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("请选择用户");
        }
        boolean autoPopDon = false;
        // 自动提现
        if (isAutoPopDone != null && isAutoPopDone == 1) {
            autoPopDon = true;
        }
        if (autoPopDon) {
            if (actualTransferMoney == null || actualTransferMoney <= 0) {
                return AjaxResult.errorResult("实际支持金额不能为空");
            }
//            if (actualTransferMoney < 1.0d) {
//                return AjaxResult.errorResult("微信或支付宝尚不支持1元以下打款");
//            }
        }
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (null == userInfo) {
            return AjaxResult.errorResult("当前用户不存在，请查证");
        }
        //
        boolean isHas = false;
        Double money = 0d;
        UserWalletPop userWalletPop = null;
        StringBuffer sbSelect = new StringBuffer();
        sbSelect.append("select * from ").append(PojoTables.USER_WALLET_POP).append(" where id = ").append(id);
        try {
            userWalletPop = (UserWalletPop) UserDaoSql.getInstance().getObject(UserWalletPop.class, sbSelect.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("获取当前提现记录失败，请稍后再试");
        }
        if (null != userWalletPop) {
            isHas = true;
            money = userWalletPop.getMoney();
            if (autoPopDon) {
                if (userWalletPop.getChannel() == null
                        || (!userWalletPop.getChannel().equals(PAY_TYPE.WX) && !userWalletPop.getChannel().equals(PAY_TYPE.ALLIPAY))) {
                    return AjaxResult.errorResult("当前自动提现仅支持微信和支付宝");
                }
                if (actualTransferMoney > userWalletPop.getMoney()) {
                    return AjaxResult.errorResult("打款金额不能大于提现金额");
                }
            }
        }
        if (isHas) {
            if (autoPopDon) {
                if (userWalletPop.getIsDone() != 0) {
                    return AjaxResult.errorResult("当前提现状态不可操作");
                }
                try {
                    UserWalletMan.alipayOrWxTransfer(username, userInfo, userWalletPop, actualTransferMoney, user.getUsername());
                } catch (Exception e) {
                    e.printStackTrace();
                    return AjaxResult.errorResult(e.getMessage());
                }
            } else {
                //  外币支付
                if (null != SYS_SETTINGS.USE_MAIN_CURRENCY_PAY && 0 == SYS_SETTINGS.USE_MAIN_CURRENCY_PAY && ValidateUtil.isAbsDouble(userWalletPop.getFcMoney())) {
                    // ps 用户提现记录表中的字段与用户钱包的字段意义恰相反 money标识人民币  fcMoney 表示 其他的币种
                    money = userWalletPop.getFcMoney();
                }
                if (!ValidateUtil.isAbsDouble(actualTransferMoney)) {
                    actualTransferMoney = money;
                }
                if (actualTransferMoney > money) {
                    return AjaxResult.errorResult("超出此条记录提现金额");
                }
                String actualMoneyStr = "";
                if (null != SYS_SETTINGS.USE_MAIN_CURRENCY_PAY && 0 == SYS_SETTINGS.USE_MAIN_CURRENCY_PAY && ValidateUtil.isAbsDouble(userWalletPop.getFcMoney()) && ValidateUtil.isAbsDouble(SYS_SETTINGS.EXCHANGE_RATE)) {
                    // 外币支付
                    actualMoneyStr += ", actualFcTransferMoney =" + actualTransferMoney;
                    Double tempMoney = JYMathDoubleUtils.mul(actualTransferMoney, SYS_SETTINGS.EXCHANGE_RATE);
                    actualMoneyStr += ", actualTransferMoney =" + tempMoney;
                } else {
                    actualMoneyStr += ", actualFcTransferMoney =" + actualTransferMoney + ", actualTransferMoney =" + actualTransferMoney;
                }
                // 提现金额
                //设置为已提现
                String voucherStr = "";
                // 上传凭证信息
                if (uploadInfo != null && uploadInfo.getImage1() != null) {
                    //存储图片
                    String filePath1 = JYImageUtils.saveImage(SYS_CONFIG_PATH.VOUCHER_IMAGE, uploadInfo.getImage1());
                    if (null == filePath1) {
                        return AjaxResult.errorResult("上传凭证失败");
                    }
                    voucherStr += " ,voucherImageUrl ='" + filePath1 + "' ";
                }
                if (ValidateUtil.isNotNull(note)) {
                    voucherStr += " ,note='" + note + "' ";
                }
                Long time = DateUtils.getCurrTime();
                StringBuilder sb = new StringBuilder();
                sb.append("update ").append(PojoTables.USER_WALLET_POP).append(" set isDone = 1,updateUser = '").append(user.getUsername())
                        .append("',popTime = ").append(time)
                        .append(voucherStr)
                        .append(actualMoneyStr)
                        .append(" where id =").append(id).append(" and username = '").append(username).append("' and isDone = 0 and delFlag = 0");
                try {
                    UserDaoSql.getInstance().executeBySql(sb.toString());
                } catch (SQLException e) {
                    e.printStackTrace();
                    return AjaxResult.errorResult("设置失败，请稍后再试");
                }
//                //  外币支付
//                if (null != SYS_SETTINGS.USE_MAIN_CURRENCY_PAY && 0 == SYS_SETTINGS.USE_MAIN_CURRENCY_PAY && ValidateUtil.isAbsDouble(userWalletPop.getFcMoney())) {
//                    // ps 用户提现记录表中的字段与用户钱包的字段意义恰相反 money标识人民币  fcMoney 表示 其他的币种
//                    money = userWalletPop.getFcMoney();
//                }
                //更新用户账号余额信息
                UserWalletMan.saveOrUpdateUserWallet(username, userInfo.getUserType(), null, ShopWalletMan.POP_SUCCESS, money, 0d, user.getUsername());
                //给用户推送通知
                Notice.publishNotice2Person(null, username, userInfo.getUserType(), NoticeType.system, "提现申请", "您的提现申请已通过，预计3-5个工作日到账。");
            }
//            //设置为已提现
//            Long time = DateUtils.getCurrTime();
//            StringBuilder sb = new StringBuilder();
//            sb.append("update ").append(PojoTables.USER_WALLET_POP).append(" set isDone = 1,updateUser = '").append(user.getUsername())
//                    .append("',popTime = ").append(time).append(" where id =").append(id).append(" and username = '").append(username).append("' and isDone = 0 and delFlag = 0");
//            try {
//                UserDaoSql.getInstance().executeBySql(sb.toString());
//            } catch (SQLException e) {
//                e.printStackTrace();
//                return AjaxResult.errorResult("设置失败，请稍后再试");
//            }
//
//            //更新用户账号余额信息
//            UserWalletMan.saveOrUpdateUserWallet(username, userInfo.getUserType(), null, ShopWalletMan.POP_SUCCESS, money, 0d, user.getUsername());
//
//            //给用户推送通知
//            Notice.publishNotice2Person(null, username, userInfo.getUserType(), NoticeType.system, "提现申请", "您的提现申请已通过，预计3-5个工作日到账。");
        } else {
            return AjaxResult.errorResult("未找到相对应的提现申请记录");
        }

        return AjaxResult.successResult();
    }

    // 用户提现申请(审核代理提现正在使用)
    @RequestMapping(method = RequestMethod.POST, value = "/admin/user/pop/done")
    @ResponseBody
    public String user_wallet_pop_done_(String token, String username, Long id, Double actualTransferMoney, Integer isAutoPopDone) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //验证是否有登录权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (ValidateUtil.isNotID(id)) {
            return AjaxResult.errorResult("请选择需要为已提现的记录");
        }

        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("请选择用户");
        }
        boolean autoPopDon = false;
        // 自动提现
        if (isAutoPopDone != null && isAutoPopDone == 1) {
            autoPopDon = true;
        }
        if (autoPopDon) {
            if (actualTransferMoney == null || actualTransferMoney <= 0) {
                return AjaxResult.errorResult("实际支持金额不能为空");
            }
//            if (actualTransferMoney < 1.0d) {
//                return AjaxResult.errorResult("微信或支付宝尚不支持1元以下打款");
//            }
        }

        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (null == userInfo) {
            return AjaxResult.errorResult("当前用户不存在，请查证");
        }
        //
        boolean isHas = false;
        Double money = 0d;
        UserWalletPop userWalletPop = null;
        StringBuffer sbSelect = new StringBuffer();
        sbSelect.append("select * from ").append(PojoTables.USER_WALLET_POP).append(" where id = ").append(id);
        try {
            userWalletPop = (UserWalletPop) UserDaoSql.getInstance().getObject(UserWalletPop.class, sbSelect.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("获取当前提现记录失败，请稍后再试");
        }
        if (null != userWalletPop) {
            if (autoPopDon) {
                // 自动打款的
                isHas = true;
                money = userWalletPop.getMoney();
                if (userWalletPop.getChannel() == null
                        || (!userWalletPop.getChannel().equals(PAY_TYPE.WX) && !userWalletPop.getChannel().equals(PAY_TYPE.ALLIPAY))) {
                    return AjaxResult.errorResult("当前自动提现仅支持微信和支付宝");
                }
                if (actualTransferMoney > userWalletPop.getMoney()) {
                    return AjaxResult.errorResult("打款金额不能大于提现金额");
                }
            } else {
                //线下自己打款的
                isHas = true;
                money = userWalletPop.getMoney();
            }
        }
        if (isHas) {
            if (autoPopDon) {
                try {
                    UserWalletMan.alipayOrWxTransfer(username, userInfo, userWalletPop, actualTransferMoney, user.getUsername());
                } catch (Exception e) {
                    e.printStackTrace();
                    return AjaxResult.errorResult(e.getMessage());
                }
            } else {
                //设置为已提现
                Long time = DateUtils.getCurrTime();
                StringBuilder sb = new StringBuilder();
                sb.append("update ").append(PojoTables.USER_WALLET_POP).append(" set isDone = 1,updateUser = '").append(user.getUsername())
                        .append("',popTime = ").append(time).append(" where id =").append(id).append(" and username = '").append(username).append("' and isDone = 0 and delFlag = 0");
                try {
                    UserDaoSql.getInstance().executeBySql(sb.toString());
                } catch (SQLException e) {
                    e.printStackTrace();
                    return AjaxResult.errorResult("设置失败，请稍后再试");
                }
                //更新用户账号余额信息
                UserWalletMan.saveOrUpdateUserWallet(username, userInfo.getUserType(), null, ShopWalletMan.POP_SUCCESS, money, 0d, user.getUsername());

                //给用户推送通知
                Notice.publishNotice2Person(null, username, userInfo.getUserType(), NoticeType.system, "提现申请", "您的提现申请已通过，预计3-5个工作日到账。");
            }
        } else {
            return AjaxResult.errorResult("未找到相对应的提现申请记录");
        }

        return AjaxResult.successResult();
    }

    //管理员设置为拒绝打款
    @RequestMapping(method = RequestMethod.POST, value = "/admin/user/pop/refuse")
    @ResponseBody
    public String user_wallet_pop_refund_admin(String token, String username, Long id, String reason) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //验证是否有登录权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (ValidateUtil.isNotID(id)) {
            return AjaxResult.errorResult("请选择需要为已提现的记录");
        }

        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("请选择用户");
        }

        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (null == userInfo) {
            return AjaxResult.errorResult("当前用户不存在，请查证");
        }

        //
        boolean isHas = false;
        Double money = 0d;
        UserWalletPop userWalletPop = null;
        StringBuffer sbSelect = new StringBuffer();
        sbSelect.append("select * from ").append(PojoTables.USER_WALLET_POP).append(" where id = ").append(id);
        try {
            userWalletPop = (UserWalletPop) UserDaoSql.getInstance().getObject(UserWalletPop.class, sbSelect.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("获取当前提现记录失败，请稍后再试");
        }
        if (null != userWalletPop) {
            isHas = true;
            money = userWalletPop.getMoney();
        }

        if (isHas) {
            if (userWalletPop.getIsDone() != 0) {
                return AjaxResult.errorResult("操作有误,请联系客服");
            }
            //设置拒绝
            String reasonsql = "";
            if (!StringUtils.isEmpty(reason)) {
                reasonsql = ",extra1 ='" + reason + "'  ";
            }
            Long time = DateUtils.getCurrTime();
            StringBuilder sb = new StringBuilder();
            sb.append("update ").append(PojoTables.USER_WALLET_POP).append(" set isDone = 2,updateUser = '").append(user.getUsername())
                    .append("',popTime = ").append(time).append(reasonsql).append(" where id =").append(id).append(" and username = '").append(username).append("' and isDone = 0 and delFlag = 0");
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("设置失败，请稍后再试");
            }

            //更新用户账号余额信息
            UserWalletMan.saveOrUpdateUserWallet(username, userInfo.getUserType(), null, ShopWalletMan.POP_REFUSE, money, 0d, user.getUsername());

            //给用户推送通知
            Notice.publishNotice2Person(null, username, userInfo.getUserType(), NoticeType.system, "提现申请", "您的提现已被拒绝,请注意查看");
        } else {
            return AjaxResult.errorResult("未找到相对应的提现申请记录");
        }

        return AjaxResult.successResult();
    }

    //获取用户充值记录
    @RequestMapping(method = RequestMethod.POST, value = "/admin/user/wallet/in/history")
    @ResponseBody
    public String admin_wallet_in_history(String token, String username, Long startTime, Long endTime, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有权限查看");
        }

        List<UserWalletFlow> list = listOfIn(username, page, size);
        if (!ValidateUtil.isAbsList(list)) {
            return AjaxResult.successResult(0, 0, null);
        }
        Long count = userWalletInCount(username, startTime, endTime);
        if (null == count) {
            count = 0l;
        }

        return AjaxResult.successResult(count, list.size(), list);
    }


    // 用户充值管理
    @RequestMapping(method = RequestMethod.POST, value = "/admin/user/recharge")
    @ResponseBody
    public String admin_wallet_rechange(String token, String username, String city,
                                        @RequestParam(defaultValue = "1") Integer page,
                                        @RequestParam(defaultValue = "15") Integer size) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        /**
         * // 1.
         * SELECT
         *   p.username AS username,
         *   u.createTime AS userCreateTime,
         *   t3.consumePrice AS consumePrice,
         *   (w.money + w.awardMoney) AS nowMoney,
         *   u.name AS user_name,
         *   IFNULL(t3.city, '') AS city,
         *   SUM(1) AS totalCount,
         *   SUM(IFNULL(p.money, 0)) AS money,
         *   SUM(IFNULL(p.awardMoney, 0)) AS awardMoney,
         *   MAX(p.createTime) AS lastCzTime
         * FROM
         *   user_wallet_flow p
         *   LEFT JOIN user_info u
         *     ON u.`username` = p.username
         *     AND u.delFlag = 0
         *   LEFT JOIN user_wallet w
         *     ON p.username = w.username
         *     AND w.delFlag = 0
         *   LEFT JOIN
         *     (SELECT
         *       t1.username AS username,
         *       MAX(t1.id) AS id,
         *       SUM(
         *         CASE
         *           WHEN t1.`payType` = 'wallet'
         *           THEN t1.`totalPrice`
         *           ELSE 0
         *         END
         *       ) AS consumePrice,
         *       t2.`shopCity` AS city
         *     FROM
         *       order_info AS t1
         *       LEFT JOIN order_info t2
         *         ON t2.id = t1.id
         *     WHERE t1.orderStatus = 9
         *       AND t1.delFlag = 0
         *       AND t1.orderType != 5
         *       AND t1.orderType != 6
         *     GROUP BY t1.username) AS t3
         *     ON p.username = t3.username
         * WHERE (p.orderType = 5
         *     OR p.orderType = 6)
         *   AND p.delFlag = 0
         *   AND p.flowType = 1
         * GROUP BY p.username
         * ORDER BY lastCzTime DESC
         */
        /** 2.
         * SELECT t.username ,
         *  t.totalCount,
         * 	t.money,
         * 	t.awardMoney,
         * 	t.lastCzTime,
         * 	u.name,
         * 	t3.consumePrice,
         * 	IFNULL(t3.city,'') AS city,
         * 	(w.money + w.awardMoney) AS nowMoney,
         * 	u.createTime AS userCreateTime
         *
         *  FROM
         * (SELECT
         *   p.username AS username,
         *   SUM(1) AS totalCount,
         *   SUM(IFNULL(p.money, 0)) AS money,
         *   SUM(IFNULL(p.awardMoney, 0)) AS awardMoney,
         *   MAX(p.createTime) AS lastCzTime
         * FROM
         *   user_wallet_flow p
         * WHERE (p.orderType = 5 OR p.orderType = 6)
         *   AND p.delFlag = 0
         *   AND p.flowType = 1
         * GROUP BY p.username
         * ) AS t
         *   LEFT JOIN user_info AS u ON u.username = t.username AND  u.delFlag = 0
         *   LEFT JOIN user_wallet w
         *     ON t.username = w.username AND w.delFlag = 0
         *   LEFT JOIN
         *     (SELECT
         *       t1.username AS username,
         *       MAX(t1.id) AS id,
         *       SUM(
         *         CASE
         *           WHEN t1.`payType` = 'wallet'
         *           THEN t1.`totalPrice`
         *           ELSE 0
         *         END
         *       ) AS consumePrice,
         *       t2.`shopCity` AS city
         *     FROM
         *       order_info AS t1
         *       LEFT JOIN order_info t2
         *         ON t2.id = t1.id
         *     WHERE t1.orderStatus = 9
         *       AND t1.delFlag = 0
         *       AND t1.orderType != 5
         *       AND t1.orderType != 6
         *     GROUP BY t1.username) AS t3
         *     ON t.username = t3.username
         *
         *
         * ORDER BY t.lastCzTime DESC
         */
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT ")
                .append(" p.username as username, ")
                .append(" u.createTime AS userCreateTime,")
                .append(" u.userType AS userType,")
                .append(" t3.consumePrice AS consumePrice,")
                .append(" (w.money + w.awardMoney) AS nowMoney,")
                .append("  u.name AS user_name,")
                .append("  IFNULL(t3.city,'') AS city,")
                .append("  SUM(1) AS totalCzCount,")
//                .append("  (SUM(IFNULL(p.money,0)) + SUM(IFNULL(p.awardMoney,0)))  AS totalMoney,")
                .append("  SUM(IFNULL(p.money,0)) AS czMoney,")
                .append("  SUM(IFNULL(p.awardMoney,0)) AS czAwardMoney,")
                .append("   MAX(p.createTime) AS lastCzTime ")
                .append("FROM ")
                .append(" ").append(PojoTables.USER_WALLET_FLOW).append(" p ")
                .append(" LEFT JOIN ").append(PojoTables.UserInfo).append(" u ")
                .append(" ON u.`username` = p.username and u.delFlag = 0 ")
                .append(" LEFT JOIN ").append(PojoTables.USER_WALLET).append(" w ")
                .append(" ON p.username = w.username  and w.delFlag = 0")
                .append(" LEFT JOIN ( ")
                .append("         SELECT t1.username AS username ,MAX(t1.id) AS id, " +
                        "           SUM(CASE WHEN t1.`payType`='wallet' THEN t1.`totalPrice` ELSE 0 END) AS consumePrice,t2.`shopCity` AS city FROM ").append(PojoTables.OrderInfo).append(" AS  t1")
                .append("               LEFT JOIN ").append(PojoTables.OrderInfo).append(" t2 ON t2.id =t1.id ")
                .append("         WHERE t1.orderStatus = ").append(ORDER_STATUS.OVER).append(" AND t1.delFlag =0 AND t1.orderType != ").append(ORDER_TYPE.WALLET_IN).append(" and t1.orderType != ").append(ORDER_TYPE.WALLET_DEPOSIT_IN).append(" GROUP BY t1.username ")
                .append("    ) AS t3  ON p.username = t3.username ")
                .append(" WHERE (p.orderType =  ").append(ORDER_TYPE.WALLET_IN)
                .append(" or p.orderType = ").append(ORDER_TYPE.WALLET_DEPOSIT_IN).append(")")
                .append(" AND p.delFlag = 0 ")
                .append(" AND p.flowType = 1 ");
        if (ValidateUtil.isNotNull(city)) {
            sql.append(" and u.city = '").append(city).append("'");
        }
        if (ValidateUtil.isNotNull(username)) {
            sql.append(" and p.username like '%").append(username).append("%'");
        }
        sql.append(" GROUP BY p.username order by lastCzTime desc   ");
        List<HashMap<String, Object>> mapList = null;
        try {
            mapList = UserDaoSql.getInstance().queryBySql(sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("查询失败,请稍后重试");
        }
        if (mapList != null && mapList.size() > 0) {
            JYPageUtils.PageList pageList = JYPageUtils.getList(mapList, page, size);
            // 消费的钱拼接进来
            return AjaxResult.successResult(pageList.list, pageList.totalCount);
        }
        return AjaxResult.successResult(null, 0);
    }

    // 查看用户的充值
    // 用户充值管理
    @RequestMapping(method = RequestMethod.POST, value = "/admin/user/recharge/history")
    @ResponseBody
    public String admin_wallet_rechange_history(String token, String username) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("用户账号不能为空");
        }
        StringBuilder sql = new StringBuilder();
        sql.append(" select * from ")
                .append(PojoTables.USER_WALLET_FLOW)
                .append(" where delFlag = 0 and username ='").append(username).append("'")
                .append(" and (orderType = ").append(ORDER_TYPE.WALLET_IN)
                .append(" or orderType = ").append(ORDER_TYPE.WALLET_DEPOSIT_IN).append(")")
                .append(" and flowType = ").append(UserWalletFlowType.FLOW_INCOME);
        List<UserWalletFlow> list = null;
        try {
            list = (List<UserWalletFlow>) UserDaoSql.getInstance().list(UserWalletFlow.class, sql.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("获取失败,请稍后重试");
        }
        if (list != null && list.size() > 0) {
            return AjaxResult.successResult(list.size(), list);
        }
        return AjaxResult.successResult(0, null);
    }

    // 查看用户的钱包购买的订单的金额
    @RequestMapping(method = RequestMethod.POST, value = "/admin/user/use/recharge/order/list")
    @ResponseBody
    public String admin_wallet_rechange_order(String token, String username,
                                              @RequestParam(defaultValue = "1") Integer page,
                                              @RequestParam(defaultValue = "20") Integer size) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("用户账号不能为空");
        }
        StringBuilder sql = new StringBuilder();
        sql.append(" select * from ").append(PojoTables.OrderInfo)
                .append(" where delFlag = 0 and orderStatus = ").append(ORDER_STATUS.OVER)
                .append("  and isRefundApply != ").append(REFUND_APPLY_STATUS.PASS)
                .append(" and payType ='").append(PAY_TYPE.WALLET).append("'")
                .append(" and username ='").append(username).append("'");
        List<OrderInfo> list = null;
        try {
            list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("查询失败,请稍后重试");
        }
        if (list != null && list.size() > 0) {
            JYPageUtils.PageList pageList = JYPageUtils.getList(list, page, size);
            return AjaxResult.successResult(pageList.list, pageList.totalCount);
        }
        return AjaxResult.successResult(null, 0);
    }


    //扣除押金
    @RequestMapping(method = RequestMethod.POST, value = "/admin/user/wallet/deposit/pop")
    @ResponseBody
    public String admin_user_wallet_DEPOSIT_pop(String token, String sysAppKey, String username, Double money, String reason) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("请选择要扣除押金的账号");
        }
        if (ValidateUtil.isNotAbsDouble(money)) {
            return AjaxResult.errorResult("请输入正确的金额");
        }

        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (null == userInfo) {
            return AjaxResult.errorResult("用户不存在，无法操作");
        }

        UserWallet wallet = UserWalletMemory.getInstance().getWallet(username);
        ResultInfo resultInfo = moneyPopSave(username, userInfo.getUserType(), user.getUsername(), wallet, money, null, UserWalletMan.DEPOSIT_FORCE_OUT, reason, true, user.getUserType());//强制扣除
        // ResultInfo resultInfo = moneyPopSave(username, userInfo.getUserType(), user.getUsername(), wallet, money, null, UserWalletMan.DEPOSIT_FORCE_OUT, reason, true);//强制扣除
        if (null != resultInfo && !resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }


        //发送一条订单通知
        Notice.publishNotice2Person(sysAppKey, username, JPushMessage.POSTMAN, NoticeType.system, "系统消息", "由于您在工作中未按照协议执行平台规定，现需扣除您部分押金，如有任何疑问请致电4008-730-110");

        return AjaxResult.successResult();
    }


    //查询所有已交押金的用户
    @RequestMapping(method = RequestMethod.POST, value = "/admin/wallet/deposit/list")
    @ResponseBody
    public String user_wallet__admin(String token, String username, Long startTime, Long endTime, Integer userType, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //验证是否有登录权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (null == page) {
            page = 1;
        }
        if (null == size) {
            size = 20;
        }

        QueryCondition query = QueryCondition.getInstance();
        Expression expression = Expression.getInstance();
        expression.addChild("delFlag", 0);
//        expression.addChild("depositMoney", ">", 0);
//        if (null != userType) {
//            expression.addChild("userType", userType);
//        }
        if (ValidateUtil.isNotNull(username)) {
            expression.addChild("username", "like", username);
        }
        if (null != startTime) {
            expression.addChild("createTime", ">=", startTime);
        }
        if (null != endTime) {
            expression.addChild("createTime", "<=", endTime);
        }

        query.addCondition(expression);//所有未删除的店铺
        query.setPage(page);
        query.setSize(size);
        String sql = DaoUtils.getSql(PojoTables.USER_WALLET, query);
        String sqlCount = DaoUtils.getSqlCount(PojoTables.USER_WALLET, query);
        List<UserWallet> list = null;
        Long totalCount = 0l;
        try {
            list = (List<UserWallet>) UserDaoSql.getInstance().list(UserWallet.class, sql);
            totalCount = UserDaoSql.getInstance().getCount(sqlCount);
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("查询失败，请稍后再试");
        }

        if (null == totalCount) {
            totalCount = 0l;
        }

        if (ValidateUtil.isAbsList(list)) {
            List<UserWalletVO> voList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                if (ValidateUtil.isNull(list.get(i).getUsername())) {
                    continue;
                }

                UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(list.get(i).getUsername());
                if (null == userInfo) {
                    continue;
                }

                UserWalletVO vo = new UserWalletVO();
                try {
                    ObjectUtils.copyPropertiesExclude(list.get(i), vo, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }

                vo.setName(userInfo.getName());
                vo.setImageUrl(userInfo.getSignPhoto());
                voList.add(vo);
            }
            return AjaxResult.successResult(totalCount, voList.size(), voList);
        }


        return AjaxResult.successResult(0, 0, null);
    }


    //查询所有已交押金的用户(带城市检索)
    @RequestMapping(method = RequestMethod.POST, value = "/admin/wallet/deposit/list/V2")
    @ResponseBody
    public String user_wallet__admin_V2(String token, String username, String province, String county, String city, Long startTime, Long endTime, Integer userType, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //验证是否有登录权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (null == page) {
            page = 1;
        }
        if (null == size) {
            size = 20;
        }
        if (null == userType) {
            userType = UserType.POSTMAN;
        }


        Long totalCount = 0l;

        String timeStr = "";
        if (null != startTime && null != endTime) {
            timeStr = " and a.createTime >= " + startTime + " and a.createTime <= " + endTime;
        }

        StringBuffer sb = new StringBuffer();
        switch (userType) {
            case UserType.SHOP_OWNER: {//店主
                sb.append(" FROM ").append(PojoTables.USER_WALLET).append(" a ")
                        .append(" left join ").append(PojoTables.ShopInfo).append(" b on a.username = b.ownUsername")
                        .append(" where b.delFlag = 0 and a.delFlag =0 ").append(timeStr);

            }
            break;
            case UserType.POSTMAN: {//配送员
                sb.append(" FROM ").append(PojoTables.USER_WALLET).append(" a ")
                        .append(" left join ").append(PojoTables.CityPostman).append(" b on a.username = b.username")
                        .append(" where b.delFlag = 0 and a.delFlag =0 ").append(timeStr);
            }
            break;
        }

        if (ValidateUtil.isNotNull(username)) {
            sb.append(" and a.username ='").append(username).append("'");
        }
        if (ValidateUtil.isNotNull(province)) {
            sb.append(" and b.province ='").append(province).append("'");
        }
        if (ValidateUtil.isNotNull(city)) {
            sb.append(" and b.city ='").append(city).append("'");
        }
        if (ValidateUtil.isNotNull(county)) {
            sb.append(" and b.county ='").append(county).append("'");
        }

//        sb.append(" and a.userType= ").append(userType);


        try {
            StringBuffer sbCount = new StringBuffer();
            sbCount.append("select count(1) counts ");
            sbCount.append(sb.toString());
            totalCount = UserDaoSql.getInstance().getCount(sbCount.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("查询失败，请稍后再试");
        }

        List<?> list = null;
        try {
            StringBuffer sbSql = new StringBuffer();
            sbSql.append("SELECT a.*, b.province ,b.city ,b.county ");
            sbSql.append(sb.toString());
            sbSql.append(" LIMIT ").append((page - 1) * size).append(",").append(size);
            list = UserDaoSql.getInstance().list(UserWalletVO.class, sbSql.toString());

        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("查询失败，请稍后再试");
        }

        if (ValidateUtil.isAbsList(list)) {
            List<UserWalletVO> voList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                UserWalletVO vo = (UserWalletVO) list.get(i);
                if (null == vo) {
                    continue;
                }
                if (ValidateUtil.isNull(vo.getUsername())) {
                    continue;
                }

                UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(vo.getUsername());
                if (null == userInfo) {
                    continue;
                }

                try {
                    ObjectUtils.copyPropertiesExclude(list.get(i), vo, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }

                vo.setName(userInfo.getName());
                vo.setImageUrl(userInfo.getSignPhoto());
                ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(vo.getUsername());
                if (shopInfo != null) {
                    ShopInfoVO shopVo = new ShopInfoVO();
                    BeanUtils.copyProperties(shopInfo, shopVo);
                    vo.setShopInfo(shopVo);
                } else if (shopInfo == null) {
                    CityPostman postman = CityPostmanMemory.getInstance().getPostman(vo.getUsername());
                    if (postman != null) {
                        CityPostmanVO postmanVO = new CityPostmanVO();
                        BeanUtils.copyProperties(postman, postmanVO);
                        vo.setCityPostman(postmanVO);
                    }
                }
                voList.add(vo);
            }
            return AjaxResult.successResult(totalCount, voList.size(), voList);
        }

        return AjaxResult.successResult(0, 0, null);
    }


    // 提现记录 BY LMY（检索城市）
    @RequestMapping(method = RequestMethod.POST, value = "/admin/wallet/pop/history/V2")
    @ResponseBody
    public String user_wallet_history_admin_V2(String token, String username, Integer userType, Integer popType, Integer sortType, Integer postmanType,
                                               Long startTime, Long endTime, Integer isDone, String province, String county, String city,
                                               Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //验证是否有登录权限
        if (!User.getInstance().hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (!ValidateUtil.isAbsInteger(userType)) {
            return AjaxResult.errorResult("用户类型不能为空");
        }

        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }
        Long totalCount = 0l;

        String timeStr = "";
        if (null != startTime && null != endTime) {
            timeStr = " and a.createTime >= " + startTime + " and a.createTime <= " + endTime;
        }
//        if (null != endTime) {
//            timeStr = " and a.createTime <= " + endTime;
//        }

        StringBuffer sb = new StringBuffer();
        if (0 == userType - UserType.ADMIN) {
            sb.append(" FROM ").append(PojoTables.USER_WALLET_POP).append(" a ")
                    .append(" left join ").append(PojoTables.SysCityAdmin).append(" b on a.username = b.username ")
                    .append(" where b.id is not null and b.delFlag = 0 and a.delFlag =0 ").append(timeStr);
        } else if (0 == userType - UserType.POSTMAN) {
            sb.append(" FROM ").append(PojoTables.USER_WALLET_POP).append(" a ")
                    .append(" left join ").append(PojoTables.CityPostman).append(" b on a.username = b.username")
                    .append(" where b.delFlag = 0 and a.delFlag =0 ").append(timeStr);
            if (postmanType != null) {
                sb.append(" and b.type = ").append(postmanType).append(" ");
            }
            sb.append(" and (a.userPopType is NUll  or a.userPopType =").append(userType).append(") ");
        } else {
            sb.append(" FROM ").append(PojoTables.USER_WALLET_POP).append(" a ")
                    .append(" left join ").append(PojoTables.ShopInfo).append(" b on a.username = b.ownUsername ")
                    .append(" where b.id is not null and b.delFlag = 0 and a.delFlag =0 ").append(timeStr);
            sb.append(" and (a.userPopType is NUll  or a.userPopType =").append(userType).append(") ");
        }

        //isDone  0所有 1已提现  2所有未提现
        if (ValidateUtil.isAbsInteger(isDone) && isDone > 0) {
            if (0 == 3 - isDone) {
                // 被拒绝
                sb.append(" and a.isDone=2 ");
            } else if (0 == 2 - isDone) {
                sb.append(" and a.isDone=0 ");
            } else {
                sb.append(" and a.isDone=1 ");
            }
        }
        if (null != popType) {
            // 2余额提现 7押金提现 8扣除押金
            sb.append(" and a.popType= ").append(popType);
        }
        if (ValidateUtil.isNotNull(username)) {
            sb.append(" and a.username ='").append(username).append("'");
        }
        if (ValidateUtil.isNotNull(province)) {
            sb.append(" and b.province ='").append(province).append("'");
        }
        if (ValidateUtil.isNotNull(city)) {
            sb.append(" and b.city ='").append(city).append("'");
        }
        if (ValidateUtil.isNotNull(county)) {
            sb.append(" and b.county ='").append(county).append("'");
        }
        try {
            StringBuffer sbCount = new StringBuffer();
            sbCount.append("select count(1) counts ");
            sbCount.append(sb.toString());
            totalCount = UserDaoSql.getInstance().getCount(sbCount.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("查询失败，请稍后再试");
        }
        String sortStr = "";
        if (sortType != null) {
            switch (sortType) {
                case 0:
                    break;
                case 1:
                    // 时间降序
                    sortStr = " order by a.createTime desc ";
                    break;
                case 2:
                    // 时间升序
                    sortStr = " order by a.createTime asc ";
                    break;
                case 3:
                    // 未打款优先
                    sortStr = " order by a.isDone asc , a.createTime asc ";
                    break;
                case 4:
                    // 未打款优先 倒序
                    sortStr = " order by a.isDone asc , a.createTime desc ";
                    break;
            }
        }

        List<?> list = null;
        try {
            StringBuffer sbSql = new StringBuffer();
            sbSql.append("SELECT a.*, b.province ,b.city ,b.county ");
            sbSql.append(sb.toString()).append(sortStr);
            sbSql.append(" LIMIT ").append((page - 1) * size).append(",").append(size);
            list = UserDaoSql.getInstance().list(UserWalletPopVO.class, sbSql.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("查询失败，请稍后再试");
        }

        if (ValidateUtil.isAbsList(list)) {
            List<UserWalletPopVO> voList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                UserWalletPopVO vo = (UserWalletPopVO) list.get(i);
                if (null == vo) {
                    continue;
                }
                if (ValidateUtil.isNotNull(vo.getVoucherImageUrl()) && ValidateUtil.isNotNetUrl(vo.getVoucherImageUrl())) {
                    vo.setVoucherImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + vo.getVoucherImageUrl());
                }
                if (0 == userType - UserType.POSTMAN) {
                    CityPostman postman = CityPostmanMemory.getInstance().getPostman(vo.getUsername());
                    if (postman != null) {
                        CityPostmanVO cityPostmanVO = new CityPostmanVO();
                        BeanUtils.copyProperties(postman, cityPostmanVO);
                        vo.setCityPostman(cityPostmanVO);
                    }
                }
                if (ValidateUtil.isNotNull(vo.getUsername())) {
                    UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(vo.getUsername());
                    if (null != userInfo) {
                        vo.setName(userInfo.getName());
                        if (ValidateUtil.isNotNull(userInfo.getSignPhoto())) {
                            if (ValidateUtil.isNotNetUrl(userInfo.getSignPhoto())) {
                                vo.setUserImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + userInfo.getSignPhoto());
                            } else {
                                vo.setUserImageUrl(userInfo.getSignPhoto());
                            }
                        }
                        vo.setName(userInfo.getName());
                        vo.setTelPhone(userInfo.getTelPhone());
                    }
                }
                voList.add(vo);
            }
            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(totalCount, voList.size(), voList);
            }
        }
        return AjaxResult.successResult(0, 0, null);
    }


    //--------------------------------------------------------------------------------
    //获取钱包情况
    public static UserWallet getWallet(String username) {
        UserWallet userWallet = new UserWallet();
        UserWallet userWalletMem = UserWalletMemory.getInstance().getWallet(username);
        if (null == userWalletMem) {
            userWallet = new UserWallet();
            userWallet.setMoney(0d);
        } else {
            try {
                ObjectUtils.copyPropertiesExclude(userWalletMem, userWallet, null);
            } catch (Exception e) {
                e.printStackTrace();
                userWallet = new UserWallet();
            }
        }
//        //每月提现次数限制
//        SysSetting sysSettingMonth = SysSettingMemory.getInstance().getByName(SysSettingKey.MONEY_POP_TIMES);
//        if (null != sysSettingMonth) {
//            userWallet.setMonthPopTimes(sysSettingMonth.getVal());
//        }
//        //每周提现次数
//        SysSetting sysSettingWeek = SysSettingMemory.getInstance().getByName(SysSettingKey.MONEY_POP_TIMES_WEEK);
//        if (null != sysSettingWeek) {
//            userWallet.setWeekPopTimes(sysSettingWeek.getVal());
//        }
//        //每月提现金额限制
//        SysSetting sysSettingMoney = SysSettingMemory.getInstance().getByName(SysSettingKey.MONEY_POP_TIMES_PRE);
//        if (null != sysSettingMoney) {
//            userWallet.setPopOneMoney(sysSettingMoney.getVal());
//        }


        //每月提现次数
        if (null == SYS_SETTINGS.MONEY_POP_TIMES) {
            userWallet.setMonthPopTimes(0);
        } else {
            userWallet.setMonthPopTimes(SYS_SETTINGS.MONEY_POP_TIMES);
        }

        //商户每周提现次数限制
        if (null == SYS_SETTINGS.MONEY_POP_TIMES_WEEK) {
            userWallet.setWeekPopTimes(0);
        } else {
            userWallet.setWeekPopTimes(SYS_SETTINGS.MONEY_POP_TIMES_WEEK);
        }

        //单次提现限额
        if (null == SYS_SETTINGS.MONEY_POP_TIMES_PRE) {
            userWallet.setPopOneMoney(0);
        } else {
            userWallet.setPopOneMoney(SYS_SETTINGS.MONEY_POP_TIMES_PRE);
        }

//        Double awardMoney = userWallet.getAwardMoney();
//        Double money = userWallet.getMoney();
//        if (ValidateUtil.isNotAbsDouble(money)) {
//            money = 0d;
//        }
//        if (ValidateUtil.isAbsDouble(awardMoney)) {
//            userWallet.setMoney(JYMathDoubleUtils.add(money, awardMoney));
//        }

        Double totalMoney = 0d;
        Double awardMoney = userWallet.getAwardMoney();
        Double money = userWallet.getMoney();
        if (ValidateUtil.isNotAbsDouble(money)) {
            money = 0d;
        }
        if (ValidateUtil.isNotAbsDouble(awardMoney)) {
            awardMoney = 0d;
        }
        totalMoney = JYMathDoubleUtils.add(money, awardMoney);
        userWallet.setMoney(totalMoney);

        return userWallet;
    }

    //绑定支付渠道
    private ResultInfo bindWallet(UserInfo user,
                                  String alipay, String alipayRealName,
                                  String tenpay, String tenpayopenId, String tenpayRealName,
                                  String bankUserName, String bankName, String bankCard, String bankPhone) {
        if (null == user) {
            return new ResultInfo("用户信息不存在");
        }
        boolean isHas = false;
        UserWallet userWallet = UserWalletMemory.getInstance().getWallet(user.getUsername());
        if (null == userWallet) {//没有新建
            userWallet = new UserWallet();
            userWallet.setUsername(user.getUsername());
            userWallet.setShopId(null);
            userWallet.setCreateTime(DateUtils.getCurrTime());
            userWallet.setUserType(user.getUserType());
        } else {
            isHas = true;
        }

        StringBuffer sbStr = new StringBuffer();
        boolean inputRight = false;
        //支付宝信息
        if (ValidateUtil.isNotNull(alipay) && ValidateUtil.isNotNull(alipayRealName)) {

            // 修改失败也会显示修改改后的结果 原因 对象是地址引用
//            userWallet.setAlipay(alipay);
//            userWallet.setAlipayRealName(alipayRealName);

            sbStr.append(" ,alipay='").append(alipay).append("',alipayRealName='").append(alipayRealName).append("'");
            inputRight = true;
        }
        //微信信息
        if (ValidateUtil.isNotNull(tenpay) && ValidateUtil.isNotNull(tenpayRealName)) {
//            userWallet.setTenpay(tenpay);
//            if (ValidateUtil.isNotNull(tenpayopenId)) {
//                userWallet.setTenpayopenId(tenpayopenId);
//            }
//            userWallet.setTenpayRealName(tenpayRealName);

            sbStr.append(" ,tenpay='").append(tenpay).append("',tenpayopenId='").append(tenpayopenId).append("',tenpayRealName='").append(tenpayRealName).append("'");
            inputRight = true;
        }
        // 绑定银行卡信息
        if (ValidateUtil.isNotNull(bankUserName) && ValidateUtil.isNotNull(bankName) && ValidateUtil.isNotNull(bankCard)) {
//            userWallet.setBankUserName(bankUserName);
//            userWallet.setBankName(bankName);
//            userWallet.setBankCard(bankCard);

            if (null != SYS_SETTINGS.SHOP_BIND_WALLET_CARD_NEED_CHECK && 0 == 1 - SYS_SETTINGS.SHOP_BIND_WALLET_CARD_NEED_CHECK) {
                // 开启商家银行卡绑定校验
                if (ValidateUtil.isNull(user.getIdCardNumber())) {
                    return new ResultInfo("请联系客服添加身份证号信息");
                }
                BackCardCheckResult backCardCheckResult = BackCardCheckUtil.QryBankCardBy3(bankCard, bankUserName, user.getIdCardNumber());
                if (null == backCardCheckResult) {
                    return new ResultInfo("校验银行卡信息失败，请重试");
                } else {
                    if (null == backCardCheckResult.getResult()) {
                        return new ResultInfo("校验银行卡信息失败，请重试。");
                    }
                    switch (backCardCheckResult.getResult()) {
                        case BACK_CARD_CHECK_RESULT_TYPE.TRUE: {
                            // 校验成功
                        }
                        break;
                        case BACK_CARD_CHECK_RESULT_TYPE.FALSE: {
                            // 校验失败
                            return new ResultInfo("校验银行卡信息失败，请确认是店主银行卡。");
                        }
                        case BACK_CARD_CHECK_RESULT_TYPE.NOT: {
                            // 无法认证
                            return new ResultInfo("无法认证，请重试。");
                        }
                        case BACK_CARD_CHECK_RESULT_TYPE.TIME_OUT: {
                            // 认证超时
                            return new ResultInfo("认证超时，请重试。");
                        }
                    }
                }
            }

            sbStr.append(" ,bankUserName='").append(bankUserName).append("',bankName='").append(bankName).append("',bankCard='").append(bankCard).append("'");
            inputRight = true;
        }

        if (!inputRight) {
            return new ResultInfo("请填写完整");
        }

        //保存到数据库
        if (isHas) {//更新数据库
//            StringBuilder sb = new StringBuilder();
//            sb.append("update ").append(PojoTables.USER_WALLET).append(" set alipay='").append(userWallet.getAlipay())
//                    .append("',alipayRealName='").append(userWallet.getAlipayRealName()).append("',tenpay='").append(userWallet.getTenpay())
//                    .append("',tenpayRealName='").append(userWallet.getTenpayRealName()).append("',tenpayopenId='").append(userWallet.getTenpayopenId())
//                    .append("',updateUser='").append(user.getUsername()).append("',userType = ").append(user.getUserType())
//                    .append(",bankUserName='',bankName='',bankCard=''")
//                    .append(" where username='").append(user.getUsername()).append("' and delFlag = 0 ");

            StringBuilder sb = new StringBuilder();
            sb.append("update ").append(PojoTables.USER_WALLET)
                    .append(" set updateUser='").append(user.getUsername()).append("',userType = ").append(user.getUserType())
                    .append(sbStr.toString())
                    .append(" where username='").append(user.getUsername()).append("' and delFlag = 0 ");
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return new ResultInfo("绑定失败，请稍后再试");
            }

        } else {//新建一条
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.USER_WALLET, userWallet);
            } catch (SQLException e) {
                e.printStackTrace();
                return new ResultInfo("绑定失败，请稍后再试");
            }
        }

        //在缓存中修改
        UserWalletMemory.getInstance().updateWallet(user.getUsername());


        return new ResultInfo();
    }

    // 配送员想配送公司发起提现
    public static ResultInfo postmanMoneyCompanyPop(UserInfo user, Long companyId, Double money, String channel, boolean checkCard) {
        if (ValidateUtil.isNotAbsDouble(money)) {
            return new ResultInfo("请输入正确的提现金额");
        }
        try {
            if (!PostManSalaryService.getInstance().canApplyMoney(user.getUsername(), companyId, money)) {
                return new ResultInfo("余额不足");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultInfo("申请提现失败,请稍后重试");
        }
        // 限制提现方式: 1 按次数 2 按日期 3 按次数和日期
        Boolean accordTimes = false;
        Boolean accordDates = false;
        Boolean accordTimesAndDate = false;
        if (null != SYS_SETTINGS.LIMIT_POP_TYPE) {
            if (0 == 1 - SYS_SETTINGS.LIMIT_POP_TYPE) {
                accordTimes = true;
            } else if (0 == 2 - SYS_SETTINGS.LIMIT_POP_TYPE) {
                accordDates = true;
            } else if (0 == 3 - SYS_SETTINGS.LIMIT_POP_TYPE) {
                accordTimesAndDate = true;
            } else {
                accordTimes = true;
            }
        } else {
            accordTimes = true;
        }

        if (accordTimes || accordTimesAndDate) {
            StringBuffer sb = new StringBuffer();
            sb.append("select count(1) times from ").append(PojoTables.USER_WALLET_POP).append(" where username = '").append(user.getUsername()).append("'")
                    .append(" and fromCompanyId = ").append(companyId)
                    .append(" and FROM_UNIXTIME(ifnull(createTime,0)/1000,'%Y%m') = DATE_FORMAT(NOW(),'%Y%m')");
            HashMap<String, Object> hashMap = null;
            try {
                hashMap = UserDaoSql.getInstance().queryMapBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return new ResultInfo("查询您本月提现次数时出错，请稍后再试");
            }
            if (null == hashMap) {
                return new ResultInfo("查询您本月提现次数时出错，请稍后再试");
            }
            try {
                Long times = (Long) hashMap.get("times");
                if (null == times) {
                    return new ResultInfo("查询您本月提现次数时出错，请稍后再试");
                }
                if (times > 0) {
                    if (null == SYS_SETTINGS.MONEY_POP_TIMES) {
                        if (times >= SYS_SETTINGS.MONEY_POP_TIMES) {
                            return new ResultInfo("您本月的提现次数（" + SYS_SETTINGS.MONEY_POP_TIMES + "次）已用完，请下月再来");
                        }
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
                return new ResultInfo("查询您本月提现次数时出错，请稍后再试");
            }
        } else if (accordDates || accordTimesAndDate) {
            // 按日期限制提现次数
            List<TipInfo> list = TipInfoMemory.getInstance().listOfType(-46);
            Boolean flag = true;
            Calendar cal = Calendar.getInstance();
            String day = String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
            if (ValidateUtil.isAbsList(list)) {
                for (int i = 0; i < list.size(); i++) {
                    TipInfo info = list.get(i);
                    if (info.getName().equals(day)) {
                        flag = false;
                    }
                }
            } else {
                flag = true;
            }
            if (flag) {
                return new ResultInfo("查询不在提现日期内");
            }
        }

        if (ValidateUtil.isNull(channel)) {
            return new ResultInfo("请选择提现到位置");
        }
        return postmanMoneyCompanyPopSave(user.getUsername(), user.getUserType(), user.getUsername(), companyId, money, channel, UserWalletMan.POP, null, checkCard);
    }

    private static ResultInfo postmanMoneyCompanyPopSave(String username, Integer userType, String opUsername, Long companyId, Double money, String channel, Integer manType, String note,
                                                         boolean checkCard) {
        if (null == manType) {
            manType = UserWalletMan.POP;
        }
        UserWallet userWallet = UserWalletMemory.getInstance().getWallet(username);
        if (null == userWallet) {
            return new ResultInfo("未获取到绑定信息");
        }
        UserWalletPop userWalletPop = new UserWalletPop();
        if (null != channel) {
            switch (channel) {
                case PAY_TYPE.ALLIPAY: {//支付宝
                    if (ValidateUtil.isNull(userWallet.getAlipay()) || ValidateUtil.isNull(userWallet.getAlipayRealName())) {
                        return new ResultInfo("您的支付宝信息不完整");
                    }
                    userWalletPop.setAlipay(userWallet.getAlipay());
                    userWalletPop.setAlipayRealName(userWallet.getAlipayRealName());
                }
                break;
                case PAY_TYPE.WX: {//微信
                    if (ValidateUtil.isNull(userWallet.getTenpay()) || ValidateUtil.isNull(userWallet.getTenpayRealName())) {
                        return new ResultInfo("您的微信账号信息不完整");
                    }
                    userWalletPop.setTenpay(userWallet.getTenpay());
                    userWalletPop.setTenpayopenId(userWallet.getTenpayopenId());
                    userWalletPop.setTenpayRealName(userWallet.getTenpayRealName());
                }
                break;
                case PAY_TYPE.BANK_CARD: {//银行卡
                    if (checkCard) {
                        if (ValidateUtil.isNull(userWallet.getBankUserName()) || ValidateUtil.isNull(userWallet.getBankName()) || ValidateUtil.isNull(userWallet.getBankCard())) {
                            return new ResultInfo("您的银行卡信息不完整");
                        }
                    }
                    userWalletPop.setBankUserName(userWallet.getBankUserName());
                    userWalletPop.setBankName(userWallet.getBankName());
                    userWalletPop.setBankCard(userWallet.getBankCard());
                }
                break;
                default: {
                    return new ResultInfo("请选择提现到位置.");
                }
            }
        }

        Long shopId = 0l;
        ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(username);
        if (null != shopInfo && ValidateUtil.isID(shopInfo.getId())) {
            shopId = shopInfo.getId();
        }

        Long time = DateUtils.getCurrTime();
        userWalletPop.setShopId(shopId);
        userWalletPop.setUsername(userWallet.getUsername());
        userWalletPop.setMoney(money);
        userWalletPop.setAfterMoney(JYMathDoubleUtils.sub(ValidateUtil.isAbsDouble(userWallet.getMoney()) ? userWallet.getMoney() : 0.0d, money)); // 提现后金额
        userWalletPop.setChannel(channel);
        userWalletPop.setPopType(manType);
        userWalletPop.setUserType(userType);
        userWalletPop.setIsDone(0);
        userWalletPop.setDelFlag(0);
        userWalletPop.setCreateTime(time);
        userWalletPop.setCreateUser(opUsername);
        userWalletPop.setNote(note);
        userWalletPop.setFromCompanyId(companyId);
        userWalletPop.setUserPopType(UserType.POSTMAN);

        //货币金额转换
        if (ValidateUtil.isAbsDouble(SYS_SETTINGS.EXCHANGE_RATE)) {//有汇率
            //是否使用主币提现 1使用主币支付 0使用外币支付
            if (null != SYS_SETTINGS.USE_MAIN_CURRENCY_POP && 0 == SYS_SETTINGS.USE_MAIN_CURRENCY_POP) {
                //非主币提现
                userWalletPop.setMoney(JYMathDoubleUtils.div(money, SYS_SETTINGS.EXCHANGE_RATE));
                userWalletPop.setFcMoney(money);
            } else {
                userWalletPop.setFcMoney(JYMathDoubleUtils.mul(money, SYS_SETTINGS.EXCHANGE_RATE));
            }
        }
        Connection con = null;
        try {
            con = UserDaoSql.getInstance().getConnection(true);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultInfo("数据库连接异常");
        }

        //插入数据库
        try {
            PostManSalaryService.getInstance().addApplyMoney(username, companyId, money, con);
            UserDaoSql.getInstance().saveObj(PojoTables.USER_WALLET_POP, userWalletPop, con);
            con.commit();
        } catch (Exception e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(con);
            return new ResultInfo("申请失败，请稍后再试");
        } finally {
            UserDaoSql.getInstance().close(con);
        }
        return new ResultInfo();
    }

    public static ResultInfo moneyPop(UserInfo user, Double money, String channel, Integer userPopType) {
        return moneyPop(user, money, channel, true, userPopType);
    }

    // 用户提现
    public static ResultInfo userWalletMoneyPopByUser(UserInfo user, Double money, String channel, boolean checkCard, Integer userPopType, String payPassword) {
        // yangtk 提现支付密码验证
        if (SYS_SETTINGS.VERIFY_PAYMENT_PASSWORD != null && 0 == 1 - SYS_SETTINGS.VERIFY_PAYMENT_PASSWORD) {
            if (payPassword == null || "".equals(payPassword)) {
                return new ResultInfo("请输入支付密码");
            }

            String getPayPassword = UserPwdMemory.getInstance().getPayPassword(user.getUsername());
            if (payPassword == null || "".equals(payPassword)) {
                return new ResultInfo("请先设置独立的支付密码");
            }
            // check
            try {
                payPassword = EncrypMD5.eccrypt(payPassword);
            } catch (Exception e) {
                e.printStackTrace();
                return new ResultInfo("提现失败，请联系管理员");
            }
            if (!getPayPassword.equals(payPassword)) {
                return new ResultInfo("支付密码错误，请重新输入");
            }
        }
        // end
        return moneyPop(user, money, channel, checkCard, userPopType);
    }

    // user pop type  用户是类型下提现的 // 下面的锁在线程阻塞的情况下 可能会出现问题 所以目前将方法上进行枷锁
    public static synchronized ResultInfo moneyPop(UserInfo user, Double money, String channel, boolean checkCard, Integer userPopType) {
        if (ValidateUtil.isNotAbsDouble(money)) {
            return new ResultInfo("请输入正确的提现金额");
        }
//        synchronized (popDataMap) {
//            if (!popDataMap.containsKey(user.getUsername()) || DateUtils.getCurrTime() - popDataMap.get(user.getUsername()) > 10 * 1000L) {
//                popDataMap.put(user.getUsername(), DateUtils.getCurrTime());
//            } else {
//                return new ResultInfo("请稍后重试~~");
//            }
//        }
        UserWallet userWallet = UserWalletMemory.getInstance().getWallet(user.getUsername());
        if (null == userWallet) {
            return new ResultInfo("未查询到正确的余额");
        }
        if (JYMathDoubleUtils.sub(userWallet.getMoney(), money) < 0) {
            return new ResultInfo("您的提现额度已超出余额");
        }


        // 限制提现方式: 1 按次数 2 按日期 3 按次数和日期
        Boolean accordTimes = false;
        Boolean accordDates = false;
        Boolean accordTimesAndDate = false;
        if (null != SYS_SETTINGS.LIMIT_POP_TYPE) {
            if (0 == 1 - SYS_SETTINGS.LIMIT_POP_TYPE) {
                accordTimes = true;
            } else if (0 == 2 - SYS_SETTINGS.LIMIT_POP_TYPE) {
                accordDates = true;
            } else if (0 == 3 - SYS_SETTINGS.LIMIT_POP_TYPE) {
                accordTimesAndDate = true;
            } else {
                accordTimes = true;
            }
        } else {
            accordTimes = true;
        }

        if (accordTimes || accordTimesAndDate) {
            //查询本月已提现次数
            //select count(1) times from shop_wallet_pop  where username = '15628986552'  and FROM_UNIXTIME(ifnull(popTime,0)/1000,'%Y%m') = DATE_FORMAT(NOW(),'%Y%m')
            StringBuffer sb = new StringBuffer();
            sb.append("select count(1) times from ").append(PojoTables.USER_WALLET_POP).append(" where username = '").append(user.getUsername())
                    .append("' and FROM_UNIXTIME(ifnull(createTime,0)/1000,'%Y%m') = DATE_FORMAT(NOW(),'%Y%m')");
            HashMap<String, Object> hashMap = null;
            try {
                hashMap = UserDaoSql.getInstance().queryMapBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return new ResultInfo("查询您本月提现次数时出错，请稍后再试");
            }
            if (null == hashMap) {
                return new ResultInfo("查询您本月提现次数时出错，请稍后再试");
            }
            try {
                Long times = (Long) hashMap.get("times");
                if (null == times) {
                    return new ResultInfo("查询您本月提现次数时出错，请稍后再试");
                }
                if (times > 0) {
                    //每月提现次数限制
//                SysSetting sysSettingMonth = SysSettingMemory.getInstance().getByName(SysSettingKey.MONEY_POP_TIMES);
//                if (null != sysSettingMonth && sysSettingMonth.getVal() > 0) {
//                    if (times >= sysSettingMonth.getVal()) {
//                        return new ResultInfo("您本月的提现次数（" + sysSettingMonth.getVal() + "次）已用完，请下月再来");
//                    }
//                }

                    if (null != SYS_SETTINGS.MONEY_POP_TIMES) {
                        if (times >= SYS_SETTINGS.MONEY_POP_TIMES) {
                            return new ResultInfo("您本月的提现次数（" + SYS_SETTINGS.MONEY_POP_TIMES + "次）已用完，请下月再来");
                        }
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
                return new ResultInfo("查询您本月提现次数时出错，请稍后再试");
            }
        } else if (accordDates || accordTimesAndDate) {
            // 按日期限制提现次数
            List<TipInfo> list = TipInfoMemory.getInstance().listOfType(-46);
            Boolean flag = true;
            Calendar cal = Calendar.getInstance();
            String day = String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
            if (ValidateUtil.isAbsList(list)) {
                for (int i = 0; i < list.size(); i++) {
                    TipInfo info = list.get(i);
                    if (info.getName().equals(day)) {
                        flag = false;
                    }
                }
            } else {
                flag = true;
            }
            if (flag) {
                return new ResultInfo("查询不在提现日期内");
            }
        }

        if (ValidateUtil.isNull(channel)) {
            return new ResultInfo("请选择提现到位置");
        }
        return moneyPopSave(user.getUsername(), user.getUserType(), user.getUsername(), userWallet, money, channel, UserWalletMan.POP, null, checkCard, userPopType);
        // return moneyPopSave(user.getUsername(), user.getUserType(), user.getUsername(), userWallet, money, channel, UserWalletMan.POP, null, checkCard);
    }

    //保存记录
    private static ResultInfo moneyPopSave(String username, Integer userType, String opUsername, UserWallet userWallet, Double money, String channel, Integer manType, String note,
                                           boolean checkCard, Integer userPopType) {
        if (null == userWallet) {
            return new ResultInfo("账号钱包不存在");
        }
        if (ValidateUtil.isNotAbsDouble(money)) {
            return new ResultInfo("请输入正确的金额");
        }

        if (null == manType) {
            manType = UserWalletMan.POP;
        }

        UserWalletPop userWalletPop = new UserWalletPop();
        if (null != channel) {
            switch (channel) {
                case PAY_TYPE.ALLIPAY: {//支付宝
                    if (ValidateUtil.isNull(userWallet.getAlipay()) || ValidateUtil.isNull(userWallet.getAlipayRealName())) {
                        return new ResultInfo("您的支付宝信息不完整");
                    }
                    userWalletPop.setAlipay(userWallet.getAlipay());
                    userWalletPop.setAlipayRealName(userWallet.getAlipayRealName());
                }
                break;
                case PAY_TYPE.WX: {//微信
                    if (ValidateUtil.isNull(userWallet.getTenpay()) || ValidateUtil.isNull(userWallet.getTenpayRealName())) {
                        return new ResultInfo("您的微信账号信息不完整");
                    }
                    userWalletPop.setTenpay(userWallet.getTenpay());
                    userWalletPop.setTenpayopenId(userWallet.getTenpayopenId());
                    userWalletPop.setTenpayRealName(userWallet.getTenpayRealName());
                }
                break;
                case PAY_TYPE.BANK_CARD: {//银行卡
                    if (checkCard) {
                        if (ValidateUtil.isNull(userWallet.getBankUserName()) || ValidateUtil.isNull(userWallet.getBankName()) || ValidateUtil.isNull(userWallet.getBankCard())) {
                            return new ResultInfo("您的银行卡信息不完整");
                        }
                    }
                    userWalletPop.setBankUserName(userWallet.getBankUserName());
                    userWalletPop.setBankName(userWallet.getBankName());
                    userWalletPop.setBankCard(userWallet.getBankCard());
                }
                break;
                default: {
                    return new ResultInfo("请选择提现到位置.");
                }
            }
        }

        Long shopId = 0l;
        ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(username);
        if (null != shopInfo && ValidateUtil.isID(shopInfo.getId())) {
            shopId = shopInfo.getId();
        }

        Long time = DateUtils.getCurrTime();
        userWalletPop.setShopId(shopId);
        userWalletPop.setUsername(userWallet.getUsername());
        userWalletPop.setMoney(money);
        if (manType == UserWalletMan.DEPOSIT_OUT) {
            // 押金提现申请 检测的押金情况 并不是money的情况
            userWalletPop.setAfterMoney(JYMathDoubleUtils.sub(ValidateUtil.isAbsDouble(userWallet.getDepositMoney()) ? userWallet.getDepositMoney() : 0.0d, money)); // 提现后金额
        } else {
            userWalletPop.setAfterMoney(JYMathDoubleUtils.sub(ValidateUtil.isAbsDouble(userWallet.getMoney()) ? userWallet.getMoney() : 0.0d, money)); // 提现后金额
        }
        userWalletPop.setChannel(channel);
        userWalletPop.setPopType(manType);
        userWalletPop.setUserType(userType);
        userWalletPop.setIsDone(0);
        userWalletPop.setDelFlag(0);
        userWalletPop.setCreateTime(time);
        userWalletPop.setCreateUser(opUsername);
        userWalletPop.setNote(note);
        userWalletPop.setUserPopType(userPopType);
        userWalletPop.setExchangeRate(SYS_SETTINGS.EXCHANGE_RATE);

        //货币金额转换
        if (ValidateUtil.isAbsDouble(SYS_SETTINGS.EXCHANGE_RATE)) {//有汇率
            //是否使用主币提现 1使用主币支付 0使用外币提现
            if (null != SYS_SETTINGS.USE_MAIN_CURRENCY_POP && 0 == SYS_SETTINGS.USE_MAIN_CURRENCY_POP) {
                //非主币提现
                userWalletPop.setMoney(JYMathDoubleUtils.mul(money, SYS_SETTINGS.EXCHANGE_RATE));
                userWalletPop.setFcMoney(money);
            } else {
                userWalletPop.setFcMoney(JYMathDoubleUtils.mul(money, SYS_SETTINGS.EXCHANGE_RATE));
            }
        }

        //插入数据库
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.USER_WALLET_POP, userWalletPop);
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultInfo("申请失败，请稍后再试");
        }

        //更新缓存
//        UserWalletMemory.getInstance().updateWallet(username);

        //更新余额
        ResultInfo resultInfo = UserWalletMan.saveOrUpdateUserWallet(username, userType, shopId, manType, money, 0d, opUsername);
        if (!resultInfo.isSuccess()) {
            return new ResultInfo(resultInfo.getError());
        }

        return new ResultInfo();
    }

    //查看自己的提现申请记录
    private List<UserWalletPop> listOfPop(String username, Long createTime, Integer size) {
        Boolean flag = false;//需不需要判断时间戳
        if (null != createTime && createTime > 0) {
            flag = true;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }

        QueryCondition query = QueryCondition.getInstance();
        Expression expression = Expression.getInstance();
        expression.addChild("delFlag", 0);
        expression.addChild("popType", UserWalletMan.POP);
        expression.addChild("username", username);
        if (flag) {//需要判断时间戳
            expression.addChild("createTime", "<", createTime);
        }
        query.addCondition(expression);//所有未删除的店铺
        query.setPage(1);
        query.setSize(size);

        String sql = DaoUtils.getSql(PojoTables.USER_WALLET_POP, query);
        List<UserWalletPop> list = null;
        try {
            list = (List<UserWalletPop>) UserDaoSql.getInstance().list(UserWalletPop.class, sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (!ValidateUtil.isAbsList(list)) {
            return null;
        }

        return list;
    }

    //查看自己的充值记录
    private List<UserWalletFlow> listOfIn(String username, Integer page, Integer size) {
        return listOfIn(username, page, size, null, null);
    }

    private List<UserWalletFlow> listOfIn(String username, Integer page, Integer size, Long startTime, Long endTime) {
        if (null == page) {
            page = 1;
        }
        if (null == size) {
            size = 20;
        }

//        QueryCondition query = QueryCondition.getInstance();
//        Expression expression = Expression.getInstance();
//        expression.addChild("delFlag", 0);
//        expression.addChild("orderType", UserWalletFlowType.FLOW_INCOME);//收入还是支出
//        expression.addChild("flowType", UserWalletFlowOrderType.ORDER_TYPE_WALLET);//收入类型
//        if (ValidateUtil.isNotNull(username)) {
//            expression.addChild("username", "like", username);
//        }
//        query.addCondition(expression);//所有未删除的店铺
//        query.setPage(page);
//        query.setSize(size);


        QueryCondition query = getWalletHistoryQuery(username, startTime, endTime);
        query.setPage(page);
        query.setSize(size);

        String sql = DaoUtils.getSql(PojoTables.USER_WALLET_FLOW, query);
        List<UserWalletFlow> list = null;
        try {
            list = (List<UserWalletFlow>) UserDaoSql.getInstance().list(UserWalletFlow.class, sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (!ValidateUtil.isAbsList(list)) {
            return null;
        }

        return list;
    }

    private Long userWalletInCount(String username, Long startTime, Long endTime) {
        Long count = 0l;
        String sqlCount = DaoUtils.getSqlCount(PojoTables.USER_WALLET_FLOW, getWalletHistoryQuery(username, startTime, endTime));
        try {
            count = UserDaoSql.getInstance().getCount(sqlCount);
        } catch (SQLException e) {
            e.printStackTrace();
            return 0l;
        }

        return count;
    }

    private QueryCondition getWalletHistoryQuery(String username, Long startTime, Long endTime) {

        QueryCondition query = QueryCondition.getInstance();
        Expression expression = Expression.getInstance();
        expression.addChild("delFlag", 0);
        expression.addChild("orderType", ORDER_TYPE.WALLET_IN);//收入还是支出
        expression.addChild("flowType", UserWalletFlowType.FLOW_INCOME);//收入类型
        if (null != startTime) {
            expression.addChild("createTime", ">=", startTime);
        }
        if (null != endTime) {
            expression.addChild("createTime", "<=", endTime);
        }
        if (ValidateUtil.isNotNull(username)) {
            expression.addChild("username", "like", username);
        }
        query.addCondition(expression);//所有未删除的店铺
        query.addOrders("createTime", "desc");

        return query;
    }


    //----------押金

    //查看自己的充值记录
    private List<UserWalletFlow> listOfDepositIn(String username, Integer page, Integer size) {
        if (null == page) {
            page = 1;
        }
        if (null == size) {
            size = 20;
        }

        QueryCondition query = getWalletDepositHistoryQuery(username);
        query.setPage(page);
        query.setSize(size);

        String sql = DaoUtils.getSql(PojoTables.USER_WALLET_FLOW, query);
        List<UserWalletFlow> list = null;
        try {
            list = (List<UserWalletFlow>) UserDaoSql.getInstance().list(UserWalletFlow.class, sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (!ValidateUtil.isAbsList(list)) {
            return null;
        }

        return list;
    }

    private QueryCondition getWalletDepositHistoryQuery(String username) {

        QueryCondition query = QueryCondition.getInstance();
        Expression expression = Expression.getInstance();
        expression.addChild("delFlag", 0);
        expression.addChild("orderType", ORDER_TYPE.WALLET_DEPOSIT_IN);//收入还是支出
        expression.addChild("flowType", UserWalletFlowType.FLOW_INCOME);//收入类型
        if (ValidateUtil.isNotNull(username)) {
            expression.addChild("username", "like", username);
        }
        query.addCondition(expression);//所有未删除的店铺
        query.addOrders("createTime", "desc");

        return query;

    }

    //查看自己的押金提现申请记录
    private List<UserWalletPop> listOfDepositPop(String username, Long createTime, Integer size) {
        Boolean flag = false;//需不需要判断时间戳
        if (null != createTime && createTime > 0) {
            flag = true;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }

        QueryCondition query = QueryCondition.getInstance();
        Expression expression = Expression.getInstance();
        expression.addChild("delFlag", 0);
        expression.addChild("username", username);
        expression.addChild("popType", UserWalletMan.DEPOSIT_OUT);
        if (flag) {//需要判断时间戳
            expression.addChild("createTime", "<", createTime);
        }
        query.addCondition(expression);//所有未删除的店铺
        query.setPage(1);
        query.setSize(size);

        String sql = DaoUtils.getSql(PojoTables.USER_WALLET_POP, query);
        List<UserWalletPop> list = null;
        try {
            list = (List<UserWalletPop>) UserDaoSql.getInstance().list(UserWalletPop.class, sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (!ValidateUtil.isAbsList(list)) {
            return null;
        }

        return list;
    }

    // hgj
    // 管理后台获取某人的押金充值记录
    @RequestMapping(method = RequestMethod.POST, value = "admin/user/deposit_in/history")
    @ResponseBody
    public String listOfDepositInHistory(String token, String username) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (StringUtils.isEmpty(username)) {
            return AjaxResult.errorResult("用户账号不能为空");
        }
        StringBuilder sel = new StringBuilder();
//        sel.append(" select ")
//        SELECT U.id ,U.orderNo,U.money,U.username,O.payType,U.createTime FROM user_wallet_flow  AS U
//        LEFT JOIN order_info AS O ON U.orderNo = O.orderNo
//        WHERE U.delFlag = 0 AND U.orderType = 6 AND U.flowType = 1 AND U.username = '13122221111';
//        QueryCondition query = QueryCondition.getInstance();
//        Expression expression = Expression.getInstance();
//        expression.addChild("delFlag", 0);
//        expression.addChild("orderType", ORDER_TYPE.WALLET_DEPOSIT_IN);//收入还是支出
//        expression.addChild("flowType", UserWalletFlowType.FLOW_INCOME);//收入类型
//        query.addCondition(expression);//所有未删除的店铺
//        String sql = DaoUtils.getSql(PojoTables.USER_WALLET_FLOW, query);
        sel
                .append(" SELECT U.id ,U.orderNo,U.money,U.username,O.payType,U.createTime ")
                .append("    From ").append(PojoTables.USER_WALLET_FLOW).append(" AS U ")
                .append("       LEFT JOIN ").append(PojoTables.OrderInfo).append(" AS O")
                .append("       ON U.orderNo = O.orderNo  ")
                .append("    WHERE U.delFlag = 0 AND U.orderType = ").append(ORDER_TYPE.WALLET_DEPOSIT_IN)
                .append("       AND U.flowType = ").append(UserWalletFlowType.FLOW_INCOME)
                .append("       AND U.username ='").append(username).append("'")
                .append(" order by U.createTime desc");
        List<HashMap<String, Object>> dataMaps = null;
        try {
            dataMaps = UserDaoSql.getInstance().queryBySql(sel.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("获取失败,请稍后重试");
        }
        if (ValidateUtil.isAbsList(dataMaps)) {
            return AjaxResult.successResult(dataMaps.size(), dataMaps);
        }
        return AjaxResult.successResult(0, null);
    }

    // hgj
    // 管理后台某用户的获取押金提现记录
    @RequestMapping(method = RequestMethod.POST, value = "admin/user/wallet/pop/history")
    @ResponseBody
    public String admin_get_user_deposit_out_history(String token, String username) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (StringUtils.isEmpty(username)) {
            return AjaxResult.errorResult("用户账号不能为空");
        }
        QueryCondition query = QueryCondition.getInstance();
        Expression expression = Expression.getInstance();
        expression.addChild("delFlag", 0);
        expression.addChild("username", username);
        expression.addChild("popType", UserWalletMan.DEPOSIT_OUT);
        query.addCondition(expression);//所有未删除的店铺
        String sql = DaoUtils.getSql(PojoTables.USER_WALLET_POP, query);
        List<UserWalletPop> list = null;
        try {
            list = (List<UserWalletPop>) UserDaoSql.getInstance().list(UserWalletPop.class, sql);
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("获取失败,请稍后重试");
        }
        if (ValidateUtil.isAbsList(list)) {
            Collections.sort(list, Comparator.comparingLong(UserWalletPop::getCreateTime).reversed());
            return AjaxResult.successResult(list.size(), list);
        }
        return AjaxResult.successResult(0, null);
    }


    // 配送公司查看--自己的骑手申请提现记录
    @RequestMapping(method = RequestMethod.POST, value = "/post-company/postman/pop/history")
    @ResponseBody
    public String listOfFromCompanyPop(String token, Long companyId, String username,
                                       Long startTime, Long endTime, Integer isDone,
                                       @RequestParam(defaultValue = "1") Integer page,
                                       @RequestParam(defaultValue = "20") Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        PostCompanyInfo postCompanyInfo = null;
        if (companyId == null) {
            postCompanyInfo = PostCompanyMemory.getInstance().getByUsername(user.getUsername());
        } else {
            postCompanyInfo = PostCompanyMemory.getInstance().getById(companyId);
        }
        if (postCompanyInfo == null) {
            return AjaxResult.errorResult("未获取到配送公司信息");
        }
        QueryCondition query = QueryCondition.getInstance();
        Expression expression = Expression.getInstance();
        expression.addChild("delFlag", 0);
        expression.addChild("fromCompanyId", postCompanyInfo.getId());
        if (ValidateUtil.isNotNull(username)) {
            expression.addChild("username", "like", username);
        }
        if (null != isDone) {
            if (0 == 2 - isDone) {
                // 被拒绝
                expression.addChild("isDone", 2);
            } else if (0 == 0 - isDone) {
                expression.addChild("isDone", 0);
            } else if (0 == 1 - isDone) {
                expression.addChild("isDone", 1);
            }
        }
        expression.addChild("popType", UserWalletPop.USER_POP_TYPE_BALANCE);
        if (null != startTime) {
            expression.addChild("createTime", ">=", startTime);
        }
        if (null != endTime) {
            expression.addChild("createTime", "<=", endTime);
        }
        query.addCondition(expression);
        query.setPage(page);
        query.setSize(size);
        String sql = DaoUtils.getSql(PojoTables.USER_WALLET_POP, query);
        String sqlCount = DaoUtils.getSqlCount(PojoTables.USER_WALLET_POP, query);
        List<UserWalletPop> list = null;
        Long totalCount = 0l;
        try {
            list = (List<UserWalletPop>) UserDaoSql.getInstance().list(UserWalletPop.class, sql);
            totalCount = UserDaoSql.getInstance().getCount(sqlCount);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (ValidateUtil.isAbsList(list)) {
            List<UserWalletPopVO> voList = list.stream().map(a -> a.convert2VO()).collect(Collectors.toList());
            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList, totalCount);
            }
        }
        return AjaxResult.successResult(null, 0);
    }


    // 配送公司-处理配送员的提现申请
    @RequestMapping(method = RequestMethod.POST, value = "/post-company/postman/pop/deal")
    @ResponseBody
    public String company_postman_wallet_pop_done(String token, String username, Long id, Integer isDone, String reason) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        PostCompanyInfo companyInfo = PostCompanyMemory.getInstance().getByUsername(user.getUsername());
        if (companyInfo == null) {
            return AjaxResult.errorResult("未获取到配送供公司信息");
        }
        if (ValidateUtil.isNotID(id)) {
            return AjaxResult.errorResult("请选择需要为已申请提现的记录");
        }
        if (isDone != UserWalletPop.USER_POP_STATUS_PASS && isDone != UserWalletPop.USER_POP_STATUS_DISPASS) {
            return AjaxResult.errorResult("请选择操作类型");
        }
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (null == userInfo) {
            return AjaxResult.errorResult("当前用户不存在，请查证");
        }
        boolean isHas = false;
        Double money = 0d;
        UserWalletPop userWalletPop = null;
        StringBuffer sbSelect = new StringBuffer();
        sbSelect.append("select * from ").append(PojoTables.USER_WALLET_POP).append(" where id = ").append(id)
                .append(" and username='").append(username).append("'");
        try {
            userWalletPop = (UserWalletPop) UserDaoSql.getInstance().getObject(UserWalletPop.class, sbSelect.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("获取当前提现记录失败，请稍后再试");
        }
        if (null != userWalletPop) {
            isHas = true;
            money = userWalletPop.getMoney();
        }
        if (isHas) {
            if (userWalletPop.getFromCompanyId() == null || userWalletPop.getFromCompanyId() != companyInfo.getId()) {
                return AjaxResult.errorResult("该订单不是您公司的");
            }
            if (userWalletPop.getIsDone() != 0) {
                return AjaxResult.errorResult("当前状态下不允许操作");
            }
            String reasonSql = "";
            if (isDone == UserWalletPop.USER_POP_STATUS_DISPASS) {
                if (!StringUtils.isEmpty(reason)) {
                    reasonSql = ",extra1 ='" + reason + "'";
                }
            }
            //设置为已提现
            Long time = DateUtils.getCurrTime();
            StringBuilder sb = new StringBuilder();
            sb.append("update ").append(PojoTables.USER_WALLET_POP).append(" set isDone = ").append(isDone).append(",updateUser = '").append(user.getUsername())
                    .append("',popTime = ").append(time).append(reasonSql).append(" where id =").append(id).append(" and username = '").append(username).append("' and isDone = 0 and delFlag = 0");
            Connection conn = null;
            try {
                conn = UserDaoSql.getInstance().getConnection(true);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString(), conn);
                PostManSalaryService.getInstance().applyState(username, companyInfo.getId(), userWalletPop.getMoney(), isDone == UserWalletPop.USER_POP_STATUS_PASS, conn);
                conn.commit();
            } catch (Exception e) {
                e.printStackTrace();
                UserDaoSql.getInstance().rollback(conn);
                return AjaxResult.errorResult("设置失败，请稍后再试");
            } finally {
                UserDaoSql.getInstance().close(conn);
            }
        } else {
            return AjaxResult.errorResult("未找到相对应的提现申请记录");
        }
        return AjaxResult.successResult();
    }


    // admin - 获取配送公司的提现申请记录
    @RequestMapping(method = RequestMethod.POST, value = "admin/post-company/pop/history")
    @ResponseBody
    public String post_company_pop_history(String token, String content, Long startTime, Long endTime, Integer isDone
            , @RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "20") Integer size) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        StringBuilder sql = new StringBuilder();
        sql.append(" from ").append(PojoTables.USER_WALLET_POP).append(" as pop")
                .append(" left join ").append(PojoTables.POST_COMPANY).append(" as c")
                .append(" on pop.username = c.username COLLATE utf8mb4_unicode_ci ")
                .append(" where  pop.delFlag =0 and c.delFlag = 0");
        if (ValidateUtil.isNotNull(content)) {
            sql.append(" and ( pop.username like '%").append(content).append("%' or c.companyName like  '%").append(content).append("%')");
        }
        if (isDone != null) {
            sql.append(" and isDone = ").append(isDone);
        }
        if (ValidateUtil.isAbsLong(startTime)) {
            sql.append(" and  pop.createTime >=").append(startTime);
        }
        if (ValidateUtil.isAbsLong(endTime)) {
            sql.append(" and  pop.createTime <= ").append(endTime);
        }
        long count = 0L;
        StringBuilder countSql = new StringBuilder();
        countSql.append("select count(1) as counts ").append(sql.toString());
        StringBuilder selectSql = new StringBuilder();
        selectSql.append("select pop.* ").append(sql.toString()).append(" order by pop.createTime ").append(" limit ").append((page - 1) * size).append(",").append(size);
        System.out.println(selectSql.toString());
        List<UserWalletPop> list = null;
        try {
            count = UserDaoSql.getInstance().getCount(countSql.toString());
            list = (List<UserWalletPop>) UserDaoSql.getInstance().list(UserWalletPop.class, selectSql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("获取失败,请稍后重试");
        }
        if (ValidateUtil.isAbsList(list)) {
            List<UserWalletPopVO> popVOS = list.stream().map(a -> {
                UserWalletPopVO vo = new UserWalletPopVO();
                BeanUtils.copyProperties(a, vo);
                PostCompanyInfo postCompanyInfo = PostCompanyMemory.getInstance().getByUsername(vo.getUsername());
                if (postCompanyInfo != null) {
                    vo.setPostCompany(postCompanyInfo.convert2VO());
                }
                return vo;
            }).collect(Collectors.toList());
            return AjaxResult.successResult(popVOS, count);
        }
        return AjaxResult.successResult(null, count);
    }


    //配送公司-查看自己的提现记录
    @RequestMapping(method = RequestMethod.POST, value = "/post-company/wallet/pop/history")
    @ResponseBody
    public String postman_wallet_pop_history(String token, Long startTime, Long endTime,
                                             Integer isDone,
                                             @RequestParam(defaultValue = "1") Integer page,
                                             @RequestParam(defaultValue = "20") Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        PostCompanyInfo postCompanyInfo = PostCompanyMemory.getInstance().getByUsername(user.getUsername());
        if (postCompanyInfo == null) {
            return AjaxResult.errorResult("未回去到配送公司信息");
        }
        StringBuffer sql = new StringBuffer();
        sql.append(" from  ").append(PojoTables.USER_WALLET_POP)
                .append(" where delFlag = 0 and username='").append(user.getUsername()).append("'")
                .append(" and popType = ").append(UserWalletMan.POP);
        if (ValidateUtil.isAbsLong(startTime)) {
            sql.append(" and createTime >=").append(startTime);
        }
        if (ValidateUtil.isAbsLong(endTime)) {
            sql.append(" and createTime <=").append(endTime);
        }
        if (isDone != null) {
            sql.append(" and isDone =").append(isDone);
        }

        StringBuilder countSql = new StringBuilder();
        countSql.append("select count(*) as counts ").append(sql.toString());
        StringBuilder selectSql = new StringBuilder();
        selectSql.append(" select * ").append(sql.toString())
                .append(" order by createTime desc limit ").append((page - 1) * size).append("," + size);
        System.out.println(selectSql.toString());
        long count = 0L;
        List<UserWalletPop> list = null;
        try {
            count = UserDaoSql.getInstance().getCount(countSql.toString());
            list = (List<UserWalletPop>) UserDaoSql.getInstance().list(UserWalletPop.class, selectSql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("获取失败，请稍后重试");
        }
        if (ValidateUtil.isAbsList(list)) {
            List<UserWalletPopVO> walletPopVOS = list.stream().map(a -> a.convert2VO()).collect(Collectors.toList());
            return AjaxResult.successResult(walletPopVOS, count);
        }
        return AjaxResult.successResult(null, count);
    }

    //admin - 设置配送公司提现状态
    @RequestMapping(method = RequestMethod.POST, value = "/admin/post-company/pop/deal")
    @ResponseBody
    public String user_wallet_pop_done_state(String token, String username, Long id, String reason, Integer isDone) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //验证是否有登录权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (ValidateUtil.isNotID(id)) {
            return AjaxResult.errorResult("请选择需要为申请提现的记录");
        }

        if (isDone != UserWalletPop.USER_POP_STATUS_PASS && isDone != UserWalletPop.USER_POP_STATUS_DISPASS) {
            return AjaxResult.errorResult("请选择操作类型");
        }

        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("请选择用户");
        }

        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (null == userInfo) {
            return AjaxResult.errorResult("当前用户不存在，请查证");
        }

        //
        boolean isHas = false;
        Double money = 0d;
        UserWalletPop userWalletPop = null;
        StringBuffer sbSelect = new StringBuffer();
        sbSelect.append("select * from ").append(PojoTables.USER_WALLET_POP).append(" where id = ").append(id);
        try {
            userWalletPop = (UserWalletPop) UserDaoSql.getInstance().getObject(UserWalletPop.class, sbSelect.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("获取当前提现记录失败，请稍后再试");
        }
        if (null != userWalletPop) {
            isHas = true;
            money = userWalletPop.getMoney();
        }


        if (isHas) {
            if (userWalletPop.getIsDone() != UserWalletPop.USER_POP_STATUS_APPLYING) {
                return AjaxResult.errorResult("当前状态不允许操作");
            }
            //设置拒绝
            String reasonSql = "";
            if (isDone == UserWalletPop.USER_POP_STATUS_DISPASS && !StringUtils.isEmpty(reason)) {
                reasonSql = ",extra1 ='" + reason + "'  ";
            }
            //设置为已提现
            Long time = DateUtils.getCurrTime();
            StringBuilder sb = new StringBuilder();
            sb.append("update ").append(PojoTables.USER_WALLET_POP).append(" set isDone = ").append(isDone).append(",updateUser = '").append(user.getUsername())
                    .append("',popTime = ").append(time)
                    .append(reasonSql)
                    .append(" where id =").append(id).append(" and username = '").append(username).append("' and isDone = 0 and delFlag = 0");
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("设置失败，请稍后再试");
            }
            if (isDone == UserWalletPop.USER_POP_STATUS_PASS) {
                //更新用户账号余额信息
                UserWalletMan.saveOrUpdateUserWallet(username, userInfo.getUserType(), null, UserWalletMan.POP_SUCCESS, money, 0d, user.getUsername());
            } else {
                //更新用户账号余额信息
                UserWalletMan.saveOrUpdateUserWallet(username, userInfo.getUserType(), null, ShopWalletMan.POP_REFUSE, money, 0d, user.getUsername());
            }
        } else {
            return AjaxResult.errorResult("未找到相对应的提现申请记录");
        }
        return AjaxResult.successResult();
    }

    // todo: 分销的钱提现到余额里: 申请提现到余额包
    @RequestMapping(method = RequestMethod.POST, value = "/user/distribute/money/pop/to-wallet")
    @ResponseBody
    public String distributeMoneyPopToWallet(String token, Double cash) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!ValidateUtil.isAbsDouble(cash)) {
            return AjaxResult.errorResult("金额无效");
        }
        if (SYS_SETTINGS.HAS_DISTRIBUTE_POP_TO_WALLET != 1) {
            return AjaxResult.errorResult("当前平台不支持提现到余额");
        }
        synchronized (popDataMap) {
            if (!popDataMap.containsKey(user.getUsername()) || DateUtils.getCurrTime() - popDataMap.get(user.getUsername()) > 10 * 1000L) {
                popDataMap.put(user.getUsername(), DateUtils.getCurrTime());
            } else {
                return AjaxResult.errorResult("请稍后重试~~");
            }
        }
        // 提现到 余额额对接
        ResultInfo info = UserWalletMan.distributeMoneyPop2Wallet(user.getUsername(), cash, user.getUsername());
        if (info == null || !info.isSuccess()) {
            return AjaxResult.errorResult(info == null ? "提现失败,请稍后重试" : info.getError());
        }
        return AjaxResult.successResult();
    }

}
